The System.Type
type contains the properties IsGenericTypeDefinition and ContainsGenericParameters. After reading the MSDN documentation I conclude that both properties exist to to check whether a type is an open or closed generic type.
However, I fail to see what the difference is between the two, and when you want to use one over the other.
Remarks. Use the IsGenericType property to determine whether a Type object represents a generic type. Use the ContainsGenericParameters property to determine whether a Type object represents an open constructed type or a closed constructed type.
From the point of view of reflection, the difference between a generic type and an ordinary type is that a generic type has associated with it a set of type parameters (if it is a generic type definition) or type arguments (if it is a constructed type). A generic method differs from an ordinary method in the same way.
An "open generic type" is just a generic type that doesn't yet have its type specified (e.g., CargoCrate<T> ).
Type.ContainsGenericParameters
is recursive:
var genericList = typeof(List<>); var listOfSomeUnknownTypeOfList = genericList.MakeGenericType(genericList); listOfSomeUnknownTypeOfList.IsGenericTypeDefinition; // => false listOfSomeUnknownTypeOfList.ContainsGenericParameters; // => true
What happens here is that listOfSomeUnknownTypeOfList
is not a generic type definition itself because its type parameter is known to be a List<T>
for some T. However, since the type of listOfSomeUnknownTypeOfList
is not exactly known (because its type argument is a type definition) ContainsGenericParameters
is true
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With