Friday, May 23, 2008

Invoke method with ref and out parameters

The other day I was tryin to load an assembly using .NET Reflection and invoke a method from a given class that had an ref parameter.

After a Google-search I've found this article : http://iamacamera.org/default.aspx?section=home&id=62.

In this article, the author used basic .NET types (common types) like int32 and string. But what if I have an enum that is Int32 or some other custom class?... As you can see in the article, the key is to load the "System.String&" type and get the method using the obj.GetMethod(arguments, types);

If you'll try the following code, will not work:

Type.GetType(typeof(MyNameSpace.MyClass).FullName + "&");
Type.GetType("MyNameSpace.MyClass&");

But there is a solution...

I've made a generic method that I can use over and over again... It looks like this...

public static void InvokeMethod(string assemblyName, string className, string methodName, out object result, ref object[] arguments)
{

Assembly assembly = Assembly.LoadFrom(assemblyName);
// Walk through each type in the assembly
foreach (Type type in assembly.GetTypes())
{
// Pick up a class
if (type.IsClass == true && type.Name == className)
{
// Dynamically Invoke the Object
MethodInfo info = type.GetMethod(methodName);
ParameterInfo[] pars = info.GetParameters();
Type[] types = new Type[arguments.Length];
for (int i = 0; i < types.Length; ++i)
types[i] = pars[i].ParameterType;
info = type.GetMethod(methodName, types);
result = info.Invoke(null, arguments);
return;
}
}

return null;
}
For my need, MyClass was a static class and that's why I used info.Invoke(null, arguments);... To create an instance you have to user the Activator class like this...

object ibaseObject = Activator.CreateInstance(type);
result = info.Invoke(ibaseObject, arguments);

As you can see I'm fooling .NET and make him think I can load a refrence type like "MyNameSpce.MyClass&". The solution here was the use of ParameterInfo class from where I can get the REAL runtime type of an parameter.

Hope this helps someone some day... it sure helped me...:D