Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare generic types?

Tags:

I have a class which has some properties of type List<float>, List<int> etc. Now I am quering the properties of this class through reflection so that I get a list of PropertyInfo.

I want to filter the types which are of type List<>. But the comparison

propertyInfo.PropertyType == typeof(List<>) 

fails.

I can get around this by comparing the names, i.e., the following comparison works:

propertyInfo.PropertyType.Name == typeof(List<>).Name 

I think there should be a better way to compare the Generic types. Any clues?

like image 733
nullDev Avatar asked Dec 24 '09 12:12

nullDev


People also ask

Can you compare generics in Java?

To compare generic types in Java, use the compareTo method.

How do I compare generic types in C#?

To enable two objects of a generic type parameter to be compared, they must implement the IComparable or IComparable<T>, and/or IEquatable<T> interfaces. Both versions of IComparable define the CompareTo() method and IEquatable<T> defines the Equals() method.

How do you compare a generic array in Java?

You need to specify that the type E has a compareTo method, that is the contract of the interface Comparable<T> , then this could be written as: public static <E extends Comparable<E>> void inspectArray( E[] inputArray) { ... } E extends Comparable<E> .

How do you find the type of generic type?

Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.


1 Answers

You can use:

Type type = propertyInfo.PropertyType; if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) {     ... } 
like image 105
Jon Skeet Avatar answered Oct 14 '22 16:10

Jon Skeet