Question

I have generic method of an object that I want to invoke. But I have no clue of T in that moment, all I know is type of T which is set to a property of the object.

public calass SomeClass{

    public Type SomeType { get; set; }

    public void SomeMethod<T>(){

    }    
}

...

var instance = new SomeClass();

...

Is it possible to do something like this?

instance.SomeMethod<SomeType>();
Was it helpful?

Solution

Yes, you can call it using Reflection:

var method = instance.GetType().GetMethod("SomeMethod")
             .MakeGenericMethod(instance.SomeType);

method.Invoke(instance);

Also note that SomeType is the name of your property, not the type of your property.You need to specify the type when you want to call a generic method.

OTHER TIPS

You can add the following check in SomeMethod<T>:

if (!SomeType.IsAssignableFrom(typeof(T))) throw new Exception("Expecting type stored in SomeType.");

Or I would change the class to templated:

public class SomeClass<T>
{
    public Type InstanceType { get { return typeof(T); } }

    public void SomeMethod<T> () { }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top