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
Release: 2025-01-06 16:45:40
Original
888 people have browsed it

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;
Copy after login

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<>);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template