Instantiate a class from its textual name

38,084

Solution 1

Here's what the method may look like:

private static object MagicallyCreateInstance(string className)
{
    var assembly = Assembly.GetExecutingAssembly();

    var type = assembly.GetTypes()
        .First(t => t.Name == className);

    return Activator.CreateInstance(type);
}

The code above assumes that:

  • you are looking for a class that is in the currently executing assembly (this can be adjusted - just change assembly to whatever you need)
  • there is exactly one class with the name you are looking for in that assembly
  • the class has a default constructor

Update:

Here's how to get all the classes that derive from a given class (and are defined in the same assembly):

private static IEnumerable<Type> GetDerivedTypesFor(Type baseType)
{
    var assembly = Assembly.GetExecutingAssembly();

    return assembly.GetTypes()
        .Where(baseType.IsAssignableFrom)
        .Where(t => baseType != t);
}

Solution 2

Activator.CreateInstance(Type.GetType("SomeNamespace.SomeClassName"));

or

Activator.CreateInstance(null, "SomeNamespace.SomeClassName").Unwrap();

There are also overloads where you can specify constructor arguments.

Share:
38,084
Raheel Khan
Author by

Raheel Khan

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. - Brian Kernighan

Updated on July 19, 2022

Comments

  • Raheel Khan
    Raheel Khan almost 2 years

    Don't ask me why but I need to do the following:

    string ClassName = "SomeClassName";  
    object o = MagicallyCreateInstance("SomeClassName");
    

    I want to know how many ways there are to do this is and which approach to use in which scenario.

    Examples:

    • Activator.CreateInstance
    • Assembly.GetExecutingAssembly.CreateInstance("")
    • Any other suggestions would be appreciated

    This question is not meant to be an open ended discussion because I am sure there are only so many ways this can be achieved.

  • Raheel Khan
    Raheel Khan about 12 years
    Exactly what I needed, thanks. I also need to enumerate all classes that derive this class we just created. I'm assuming assembly.GetTypes would allow that.
  • Cristian Lupascu
    Cristian Lupascu about 12 years
    @RaheelKhan I have added a code sample for getting the derived classes defined in the same assembly.
  • andrefadila
    andrefadila over 9 years
    After we got the class, can we call the method inside?
  • Cristian Lupascu
    Cristian Lupascu over 9 years
    @andrefadila Yes. Be aware though that Activator.CreateInstance returns an object and you may need to cast it first.
  • andrefadila
    andrefadila over 9 years
    Thanks for response @w0lf. So, we must cast it first. Is there any solution without cast?
  • Cristian Lupascu
    Cristian Lupascu over 9 years
    You could also call the method via reflection. (This is pretty hacky)
  • Cristian Lupascu
    Cristian Lupascu over 9 years
    Or you could cast the object not to its exact type, but to an interface that defines that method.
  • Saurabh Shah
    Saurabh Shah about 6 years
    What if the class I want to instantiate is not in the current assembly but lies in the same solution?