44

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.

5
  • A possible duplicate of stackoverflow.com/questions/648160/… Mar 24, 2012 at 19:43
  • Hmm, what are the odds that you can guess its namespace name correctly? And the assembly it comes from? Mar 24, 2012 at 19:47
  • Is the assembly the type is in already loaded or not? If this happens to be something around plugins, you might check out MEF Mar 25, 2012 at 4:42
  • Also, does the class have a no-args ctor? (Specifically, can that be assumed) Mar 25, 2012 at 4:43
  • Actually, these class namespace is known and the classes exist in the same assembly in which I need to do this. Mar 25, 2012 at 5:43

3 Answers 3

60

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);
}
8
  • 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. Mar 25, 2012 at 5:47
  • 1
    @RaheelKhan I have added a code sample for getting the derived classes defined in the same assembly. Mar 25, 2012 at 17:01
  • After we got the class, can we call the method inside? Nov 5, 2014 at 11:04
  • @andrefadila Yes. Be aware though that Activator.CreateInstance returns an object and you may need to cast it first. Nov 5, 2014 at 11:07
  • 1
    Or you could cast the object not to its exact type, but to an interface that defines that method. Nov 6, 2014 at 5:09
20
Activator.CreateInstance(Type.GetType("SomeNamespace.SomeClassName"));

or

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

There are also overloads where you can specify constructor arguments.

0

Use this way to use the class name without the fully qualified namespace:

System.Reflection.Assembly.GetExecutingAssembly().CreateInstance("myclass");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.