For a script that creates controls using reflection, I need to distinguish between
- Standard value types like
Int32 - Generic nullable types that are based on the ones above, like
Int32? - Other generic types like
List<string>
In .NET 4.5, I can use
myType.IsConstructedGenericType
in combination with
myType.IsValueType
and get
- False/True
- True/True
- True/False
However, IsConstructedGenericType is not available in earlier .NET versions. How can I accomplish this in .NET 4.0?
IsGenericTypewill do what you want for the examples you’ve given:The difference is that using
IsConstructedGenericTypewould return false fortypeof(List<>)whereasIsGenericTypewill return true. You can useType.ContainsGenericParametersto distinguish between them in .NET 2+… although even that’s not quite enough, in pathological cases:Consider
typeof(Foo<>).BaseType:IsConstructedGenericType: True (it contains one assigned type parameter)IsGenericType: TrueContainsGenericParameters: True (it still contains one unassigned type parameter)Hopefully this won’t be an issue for you.