How can I get the number of type parameters in an open genus in C #

In short, this pretty much explains my problem ...

class Foo<T> { ... }
var type = typeof(Foo<>); <-- runtime provides a RuntimeType object instance in my real code
var paramCount = ((RuntimeType)type).GetGenericParameters().Count; <-- I need this

      

The problem, of course, is that "RuntimeType" is an internal type in (I believe) mscorlib, so I cannot access it from my code.

Is there any other / better way to do this?

Update:

I have found an "ugly and probably unsafe" way to achieve basically what I want, but I am convinced that this is a bad idea (for obvious reasons) ...

var paramCount = int.Parse(type.Name.Substring(t.Name.Length-1));

      

It assumes quite a bit and just looks unpleasant. what i said ... i'm already in the world of reflection ... so it's disgusting in nature.

Surely there is a better way to do this though?

+3


source to share


1 answer


If you are using full .NET you can simply:

int num = type.GetGenericArguments().Length;

      

If you are using .NET Core see fooobar.com/questions/386402 / ... :



TypeInfo typeInfo = type.GetTypeInfo();
int num = typeInfo.IsGenericTypeDefinition
    ? typeInfo.GenericTypeParameters.Length
    : typeInfo.GenericTypeArguments.Length;

      

If you always have an open pedigree, then it's clear:

int num = type.GetTypeInfo().GenericTypeParameters.Length;

      

+3


source







All Articles