Search code examples
c#.netgenericsreflectionsystem.reflection

How do I get the typeparam names from a generic type definition?


Suppose I have a generic type definition as such:

var type = typeof(IReadOnlyDictionary<,>)

How would I get the typeparam name of the generic arguments? In the example above, I'm looking for "TKey" and "TValue"

for typeof(IList<>) I am expecting "T"

Is there any way, using reflection, to get these strings?


Solution

  • You can use Type.GetGenericParameterConstraints for this:

    var type = typeof(IReadOnlyDictionary<,>)
    var names = type.GetGenericArguments().Select(x => x.Name);
    

    See my fiddle.