How To: Call a generic method with a runtime type
By rickvdbosch
- 2 minutes read - 256 wordsProblem:
Developing a generic class that maps datasets, datatables and datarows from a legacy system to my domain model, I ran into an issue. I wanted to call a generic method with a runtime type. Lets say the method looked like this: public string DoSomething<T>(string param)
. Because I use reflection to iterate properties on a type, the type of the properties was dynamic and only known at runtime. I wanted to do something like this:
DoSomething<propertyInfo.PropertyType>("bloggingabout");
This however resulted in an error message. The tooltip on the red colored propertyInfo read “Cannot resolve symbol ‘propertyInfo’”, while the build error stated “The type or namespace name ‘propertyInfo’ could not be found (are you missing a using directive or an assembly reference?)”. This is expected behavior, because “The type argument […] can be any type recognized by the compiler.” So that says compiler. So the type is parsed (and should be known) at compile time.
Solution:
The solution is found in reflection. Taken from the MSDN article for the MethodInfo.MakeGenericMethod Mehod:
The MakeGenericMethod method allows you to write code that assigns specific types to the type parameters of a generic method definition, thus creating a MethodInfo object that represents a particular constructed method. If the ContainsGenericParameters property of this MethodInfo object returns true, you can use it to invoke the method or to create a delegate to invoke the method.
In our example, this would look something like this:
instance.GetType()
.GetMethod("DoSomething")
.MakeGenericMethod(propertyInfo.PropertyType)
.Invoke(mapper, new object[] { "bloggingabout" });
More information:
Generic Type Parameters (C# Programming Guide)
MethodInfo.MakeGenericMethod Method