Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Type.IsGenericTypeDefinition and Type.ContainsGenericParameters

Tags:

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.

like image 475
Steven Avatar asked Oct 22 '12 13:10

Steven


People also ask

What is IsGenericType?

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.

How does a generic method differ from a generic 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.

What are open Generics in C#?

An "open generic type" is just a generic type that doesn't yet have its type specified (e.g., CargoCrate<T> ).


1 Answers

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.

like image 193
Jon Avatar answered Nov 05 '22 11:11

Jon