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("")
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.
Instantiating a ClassThe new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The new operator returns a reference to the object it created.
Instantiation is the creation of a new instance of a class and is part of object-oriented programming, which is when an object is an instance of a class. Think of the generic employee. When a true employee is hired, they inherit the properties of the generic Employee class.
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:
assembly
to whatever you need)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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With