Search code examples
c#abstract-classcreateinstance

CreateInstance says it's a method by is used like a type


I have a base program that impliments an abstract class.

public abstract class AbstractClass
{
    public AbstractClass (MyObject object1, MyOtherObject object2)
    {
        Console.WriteLine("This is the abstract class");
    }

    public abstract bool Function1();
    <other abstract functions>
}

Right now I build and compile seperate versions of my application when I want to do different things and have implemented different abstract classes for these things. I find this to be tedious.

I'd like to be able to take this line of code

new MySuperSpecialClassOfThings(param1, (MyObject obj1, MyOtherObject obj2) => 
{
    return new NotAnAbstractClass(obj1, obj2);
}, true);

And change it to something like:

new MySuperSpecialClassOfThings(param1, (MyObject obj1, MyOtherObject obj2) => 
{
    return new System.Activator.CreateInstance(Type.GetType(config.NonAbstractClassName), new object[] { obj1, obj2 });
}, true);

Where config.NonAbstractClassName is a string provided in a configuration file. This fails, though, with the error: 'System.Activator.CreateInstance(System.ActivationContext, string[])' is a 'method' but is used like a 'type'

obj1 and obj2 are not strings. They are classes.

How can I do this?


Solution

  • Get rid of the new before CreateInstance:

    new MySuperSpecialClassOfThings(param1, (MyObject obj1, MyOtherObject obj2) => 
    {
        return (AbstractClass)System.Activator.CreateInstance(Type.GetType(config.NonAbstractClassName), new object[] { obj1, obj2 });
    }, true);