2

How does the code looks that would create an object of class:

string myClass = "MyClass";

Of the above type, and then call

string myMethod = "MyMethod";

On that object?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
thr
  • 19,160
  • 23
  • 93
  • 130
  • I think you need to clarify your question. Are you trying to dynamically create the type, ie, dynamically define a class, as well as dynamically call a method on that type? – orj Jan 27 '09 at 12:38

4 Answers4

10

Example, but with no error checking:

using System;
using System.Reflection;

namespace Foo
{
    class Test
    {
        static void Main()
        {
            Type type = Type.GetType("Foo.MyClass");
            object instance = Activator.CreateInstance(type);
            MethodInfo method = type.GetMethod("MyMethod");
            method.Invoke(instance, null);
        }
    }

    class MyClass
    {
        public void MyMethod()
        {
            Console.WriteLine("In MyClass.MyMethod");
        }
    }
}

Each step needs careful checking - you may not find the type, it may not have a parameterless constructor, you may not find the method, you may invoke it with the wrong argument types.

One thing to note: Type.GetType(string) needs the assembly-qualified name of the type unless it's in the currently executing assembly or mscorlib.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

I've created a library which simplifies dynamic object creation and invocation using .NET you can download the library and the code in google code: Late Binding Helper In the project you will find a Wiki page with the usage, or you can also check this article in CodeProject

Using my library, your example will look like this:

IOperationInvoker myClass = BindingFactory.CreateObjectBinding("MyClassAssembly", "MyClass");
myClass.Method("MyMethod").Invoke();

Or even shorter:

BindingFactory.CreateObjectBinding("MyClassAssembly", "MyClass")
     .Method("MyMethod")
     .Invoke();

It uses a fluent interface, and truly simplifies this kind of operations. I hope you could find it useful.

Ricardo Amores
  • 4,597
  • 1
  • 31
  • 45
2

The following assumes an object with a public constructor and a public method that returns some value but takes no parameters.

var object = Activator.CreateInstance( "MyClass" );
var result = object.GetType().GetMethod( "MyMethod" ).Invoke( object, null );
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
0

Assuming that your class is in your executing assembly, your constructor and your method is parameterless.

Type clazz = System.Reflection.Assembly.GetExecutingAssembly().GetType("MyClass");

System.Reflection.ConstructorInfo ci = clazz.GetConstructor(new Type[] { });
object instance = ci.Invoke(null); /* Send parameters instead of null here */

System.Reflection.MethodInfo mi = clazz.GetMethod("MyMethod");
mi.Invoke(instance, null); /* Send parameters instead of null here */
Serhat Ozgel
  • 23,496
  • 29
  • 102
  • 138