Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class.forName() equivalent in .NET?

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();
like image 683
mihsathe Avatar asked May 12 '11 14:05

mihsathe


People also ask

What is the class forName () does?

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.

How do I find the class forName?

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.

Which type of exception will be thrown by forName () method?

ClassNotFoundException − if the class cannot be located by the specified class loader.

What does the method class forName string className return?

forName(String className) method returns the Class object associated with the class or interface with the given string name.


2 Answers

Look at csharp-examples.net/reflection-examples. Basically you have to use typeof() and Activator.createInstance().

like image 196
Petar Minchev Avatar answered Oct 07 '22 15:10

Petar Minchev


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.

like image 24
Cheeso Avatar answered Oct 07 '22 15:10

Cheeso