Hi guys,

I have a type that implements an abstract class that is known at compile time and I want to construct at run time an instance of the type and place the reference in a variable that is of the abstract class's type.

So, to describe it a bit.. Say we have 2 class libraries (called A and B). Library A holds the abstract class and library B holds an implementation of the abstract class. A static variable in the abstract class needs to construct at run time a B object and save it in an A type variable... that is, an A type doesn't know about the existance of B on compile time..

So.. I want to read up on app domains and reflection and all those joys of the .NET but don't have the necessary time right now to do it properly so need you guys to guide me a bit on this. Hope it makes (some) sense.


Pass in to the function in class A a delegate or object that constructs class B.

abstract class A {
  public static void INeedToConstructSomeSubclass(Func<A> subclassDelegate, ...) {
    A blah = subclassDelegate();

Then just call it with

A.INeedToConstructSomeSubclass(() => new B());

You'll need some way of communicating which subclass needs to be constructed -- and it's better and more typesafe to pass in a function than something that uses reflection.

Or simply you can use interfaces to play the role of bridge

You can walk through a library looking for classes that descend from something, and then instantiate those.

CommandTemplate newcmd;
            Console.Write("Loading commands");
            Assembly a = null;
            AssemblyName n = new AssemblyName("mycmds");
            a = Assembly.Load(n);
            foreach (Type t in a.GetTypes())

                if (t.BaseType.Name == "CommandTemplate")
                    newcmd = (CommandTemplate)Activator.CreateInstance(t);

            Console.WriteLine(" Done");
commented: Excellent :) +2

Sorry for not replying earlier. What LizR described is what I was pretty much lookingfor. Cheers :)