Saturday, January 17, 2009

Reflection in .NET

The Microsoft .NET Framework makes it really simple to dynamically load a type based on configuration info provided. It comes in pretty handy for building plug-in based systems.

In today's code sample, we'll start off with a simple class:

namespace GateLib
{
public class Neptune
{
public string GetAString()
{
return "Nile River";
}
}
}

After compiling the class into a class library (DLL), we start work on our code to call the class method. Let's build a console application for simplicity sake. Here's the code we put into the Main method:

Assembly asm = Assembly.LoadFile(System.Environment.CurrentDirectory + "\\GateLib.dll");
Type ty = asm.GetType("GateLib.Neptune");
MethodInfo meth = ty.GetMethod("GetAString");
ConstructorInfo ci = ty.GetConstructor(Type.EmptyTypes);
object obj = ci.Invoke(null);
object retval = meth.Invoke(obj, null);
Console.WriteLine(retval.ToString());
Console.Read();

In this code sample, I'm using the default constructor for the Neptune class that takes no parameters (notice the Type.EmptyTypes and the null in the ci.Invoke), and the method GetAString that takes no parameters (it's the null in the meth.Invoke).

After compiling the console application, I place the class library in the same folder as the EXE, and execute the console application to get "Nile River" on-screen.

I know it doesn't do much but it's just a start. You'll probably end up doing so much more with it.

No comments: