Home >Backend Development >C++ >How Can I Verify if an Object is a Specific Generic Type (e.g., List) in C#?
Verifying Generic Type in C#
You aim to determine if an object belongs to a generic type. Your initial attempt to compare GetType() with typeof(List<>) fails to produce the desired result. Let's explore the correct approach.
To ascertain if an object is an instance of any generic type, utilize the IsGenericType property:
return list.GetType().IsGenericType;
On the other hand, if you seek to verify if it's specifically a List
return list.GetType().GetGenericTypeDefinition() == typeof(List<>);
Note that this method verifies exact type equivalence. As mentioned by Jon, a negative response doesn't conclusively imply that the object cannot be assigned to a List
The above is the detailed content of How Can I Verify if an Object is a Specific Generic Type (e.g., List) in C#?. For more information, please follow other related articles on the PHP Chinese website!