Jwalin Khatri

How to do dynamic object creation and method invocation in .NET 3.5

Posted by: jwalin on: June 2, 2009

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.

Leave a Reply

Blog Stats

  • 14,744 hits

  • jwalin: Follow the following steps 1]. open you Page in NOTEPAD. 2]. find the tag 3]. Replace the "body" like body oncontextmenu=”return false;" 4]. Sav
  • cytocine: Halu , how to put that , i mean where to put the part ?? i really dont know i hope you can help me out thanks..
  • elmerdolor: Halu , how to put that , i mean where to put the part ?? i really dont know i hope you can help me out thanks..