Friday, February 08, 2008

Dynamic Code (Using Reflection)

We can use reflection to invoke code dynamically. Here a little sample creating an Stack object from the assembly mscorlib.dll.
// Loading the assembly
string path = @"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll";
Assembly asm = Assembly.LoadFile(path);
 
// Getting a stack object type
Type stackType = asm.GetType("System.Collections.Stack");
 
// Building the constructor call
Type[] argumentTypes = Type.EmptyTypes;
ConstructorInfo ctor = stackType.GetConstructor(argumentTypes);
 
object stackObj = ctor.Invoke(new object[] { });
 
// Calling the Push method and passing by parameters the value 
// we want to push in the stack
MethodInfo mpush = stackType.GetMethod("Push");
mpush.Invoke(stackObj, new object[] { "One" });
mpush.Invoke(stackObj, new object[] { "Two" });
mpush.Invoke(stackObj, new object[] { "Three" });
 
// Getting a property value (Count)
PropertyInfo propInfo = stackType.GetProperty("Count");
int count = (int)propInfo.GetValue(stackObj, null);
 
MessageBox.Show(count.ToString());
 
// Getting values using the Pop method
string s;
 
MethodInfo mpop = stackType.GetMethod("Pop");
s = mpop.Invoke(stackObj, null) as string;
MessageBox.Show(s);
s = mpop.Invoke(stackObj, null) as string;
MessageBox.Show(s);
s = mpop.Invoke(stackObj, null) as string;
MessageBox.Show(s);
We can also create the object by using the Activator object:
object stackObj = Activator.CreateInstance(stackType);
If we need to create the object using another constructor different from the default constructor, we can achieve this:
int initialCapacity = 10;
 
// Building the constructor call with one parameter type of integer
Type[] argumentTypes = new Type[] { typeof(int) };
ConstructorInfo ctor = stackType.GetConstructor(argumentTypes);
 
// Creating the object
object stackObj = ctor.Invoke(new object[] { initialCapacity });
Or using the Activator:
int initialCapacity = 10;
 
object stackObj = Activator.CreateInstance(stackType, new object[] { initialCapacity });
For calling static methods, we need to pass null as object paramenter when using the Invoke method, here an example calling the MessageBox.Show method:
// Loading the assembly
string path = @"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll";
Assembly myAsm = Assembly.LoadFile(path);
 
// Getting the type MessageBox
Type msgBox = myAsm.GetType("System.Windows.Forms.MessageBox");
 
// Invoking the static method 'Show'
MethodInfo showMethod = msgBox.GetMethod("Show", new Type[] { typeof(string) });
showMethod.Invoke(null, new object[] { "Hello world!" });

0 comments:


View My Stats