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;
Checking for Generic List
If you need to specifically verify if the object is an instance of List
return list.GetType().GetGenericTypeDefinition() == typeof(List<>);
Note that the latter test checks for exact type equivalence. If the object inherits from List
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!