Home > Mobile >  Use Type as Generic Method Parameter
Use Type as Generic Method Parameter

Time:05-02

Let's say I have a generic method:

private static void GenericMethod<T1, T2>()
    where T1 : SomeClass1
    where T2 : SomeClass2
{
    // Stuff
}

And I have structure that maps enum to some type, like this:

private static Dictionary<Enum, (Type, Type)> mappings =
new()
{
    {
        Enum.Value,
        (typeof(DerivedFromSomeClass1), typeof(DerivedFromSomeClass2))
    }
};

Now I want to call GenericMethod and use types from mapping as a substitute to T1, T2, like so:

var mappingType1 = mappings[enum].Item1;
var mappingType2 = mappings[enum].Item2;
GenericMethod<mappingType1, mappingType2>();

Obviously you can't do this, but... is there a way to achieve what I have in mind? Like I want to map some types to enum and then use type from enum as generic type of a method (T)?

CodePudding user response:

Ok, as it turns out it is actually fairly simple. Here's how I did it:

var mappingType1 = mappings[platform.Type].Item1;
var mappingType2 = mappings[platform.Type].Item2;
var method = typeof(Class).GetMethod(nameof(GenericMethod), BindingFlags.NonPublic | BindingFlags.Static);
var genericMethod = method.MakeGenericMethod(mappingType1, mappingType2);
genericMethod.Invoke(null, null);
  • Related