Home > Backend Development > C++ > How to Check if an Object is a Generic Type in C#?

How to Check if an Object is a Generic Type in C#?

Linda Hamilton
Release: 2025-01-06 16:05:48
Original
398 people have browsed it

How to Check if an Object is a Generic Type in C#?

How to Test if an Object is of Generic Type in C#

Question:

You want to verify if an object belongs to a generic type. However, your attempt using list.GetType() == typeof(List<>) returns false. How can you perform this test correctly?

Answer:

Determine the specific type of test you need:

Checking Instance of Generic Type:

To simply check if the object is an instance of a generic type, use:

return list.GetType().IsGenericType;
Copy after login

Checking for Generic List:

If you need to specifically verify if the object is an instance of List:

return list.GetType().GetGenericTypeDefinition() == typeof(List<>);
Copy after login

Note that the latter test checks for exact type equivalence. If the object inherits from List or implements a generic interface, the test will return false.

The above is the detailed content of How to Check if an Object is a Generic Type 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