What is the C# way for dynamically getting the type of object and then creating new instances of it?
E.g. how do I accomplish the result of following Java code, but in C#:
MyClass x = (MyClass) Class.forName("classes.MyChildClass").newInstance();
The forName() method of Java Class class returns the Class object associated with the class or interface with the given name in the parameter as String.
Class forName() method in Java with Examples This class name is specified as the string parameter. Parameter: This method accepts the parameter className which is the Class for which its instance is required. Return Value: This method returns the instance of this Class with the specified class name.
ClassNotFoundException − if the class cannot be located by the specified class loader.
forName(String className) method returns the Class object associated with the class or interface with the given string name.
Look at csharp-examples.net/reflection-examples. Basically you have to use typeof()
and Activator.createInstance()
.
Simple example:
namespace Your.Namespace
{
public class Foo
{
public DateTime SixtyDaysFromNow()
{
return DateTime.Now + new TimeSpan(60,0,0,0);
}
}
public class CreateInstance1
{
public static void Main(string[] args)
{
try
{
var x = Activator.CreateInstance(null, "Your.Namespace.Foo");
Foo f = (Foo) x.Unwrap();
Console.WriteLine("Result: {0}", f.SixtyDaysFromNow().ToString("G"));
}
catch (System.Exception exc1)
{
Console.WriteLine("Exception: {0}", exc1.ToString());
}
}
}
}
Call Activator.CreateInstance()
specifying an assembly name, and a classname. The classname must be fully qualified (include all the namespaces). If the assemblyname is null, then it uses the currently running assembly. If the class you want to activate is outside the currently running assembly you need to specify the assembly with the fully qualified name.
To load from a different assembly, you need to use an overload for CreateInstance
that accepts a type, as opposed to a type name; one way to get a type for a given type name is to use Type.GetType()
, specifying the assembly-qualified name.
Most often Activator.CreateInstance()
is done using interface types, so that the instance created can be cast to the interface and you can invoke on the interface type. like this:
interface ISixty
{
DateTime SixtyDaysFromNow();
}
public class Foo : ISixty
{
public DateTime SixtyDaysFromNow()
{
return DateTime.Now + new TimeSpan(60,0,0,0);
}
}
and
var x = Activator.CreateInstance(null, "Your.Namespace.Foo");
ISixty f = (ISixty) x.Unwrap();
Console.WriteLine("Sixty days from now: {0}", f.SixtyDaysFromNow().ToString("G"));
Doing it that way, your app (the activating app) need not be aware of or reference the other assembly explicitly, at compile time.
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