2

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)?

stroibot
  • 808
  • 1
  • 11
  • 25
  • 1
    Generics in C# need to be known during compile time, they cannot be "defined" during execution without some heavy reflection stuff and a bit of magic and that's not really the approach you want to use. – user2184057 Apr 29 '22 at 13:51
  • https://stackoverflow.com/questions/12708090/is-generics-runtime-or-compile-time-polymorphism – user2184057 Apr 29 '22 at 13:52
  • https://stackoverflow.com/questions/17734247/when-is-the-generic-type-resolved-in-c – user2184057 Apr 29 '22 at 13:52
  • What is `GenericMethod` supposed to do? And how do expect the compiler to ensure that the generic constraints are fulfilled when you want to use runtime types? – JonasH Apr 29 '22 at 13:52

1 Answers1

1

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);
stroibot
  • 808
  • 1
  • 11
  • 25