Generic class instance with type from PropertyInfo.PropertyType

c#, generics, propertyinfo, reflection

Solution

You would need to do:

typeof(SampleClassToTest<>).MakeGenericType(propertyType)
       .GetMethod("SomeMethod", new Type[] {typeof(string)})
       .Invoke(null, new object[] {"some parameter"});

Ugly.

If it can at all be helped, I would advise offering a non-generic API that accepts a `Type` instance; the nice thing here is that a generic API can call into a non-generic API trivially by using `typeof(T)`.

Problem

I have classes like below: ``` public class SampleClassToTest<T> { public static Fake<T> SomeMethod(string parameter) { // some code } public static Fake<T> SomeMethod(string parameter, int anotherParameter) { //some another code } } public class Fake<T> { // some code } ``` And I want to use them in this way: ``` SampleClassToTest<MyClass>.SomeMethod("some parameter"); ``` The problem which I have is the following: type of "MyClass" I can get only from PropertyInfo instance using Reflection, so I have ``` Type propertyType = propertyInfo.PropertyType; ``` How can I do this? Any ideas? UPD. I'm trying to pass the Type to generic method. And yes, this is what I want.

Original source