I needed to be able to call a static method on a generic class today, so I thought I would post it up here to share with the world. Enjoy.
//Our Generic Class
public class SomeGenericClass<T>
{
public static char[] ConvertToCharArray(T something)
{
return something.ToString().ToCharArray();
}
}
The example code:
// Get the type of the generic class
Type typeofClassWithGenericStaticMethod = typeof(SomeGenericClass<>);
//Get a typed version of the generic type
Type type = Type.GetType("System.String");
Type[] args = new[] { type };
Type genericType = typeofClassWithGenericStaticMethod.MakeGenericType(args);
// Get a reference to the method you want to call.
MethodInfo methodInfo = genericType
.GetMethod("ConvertToCharArray", System.Reflection.BindingFlags.Static | BindingFlags.Public);
// Invoke the method with parameters. (If it doesn't have a pameter, use null instead of the object array)
object returnValue = methodInfo.Invoke(null, new object[]{"Hello World"});
char[] characters = (char[])returnValue;
foreach (char character in characters)
{
Console.Write(character);
}