Home >Backend Development >C++ >How Can I Verify if an Object is a Specific Generic Type (e.g., List) in C#?

How Can I Verify if an Object is a Specific Generic Type (e.g., List) in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-06 16:45:40886browse

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 generic type, employ this condition:

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 variable.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn