Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Detect If Type is Another Generic Type

Tags:

c#

example:

public static void DoSomething<K,V>(IDictionary<K,V> items) {    items.Keys.Each(key => {       if (items[key] **is IEnumerable<?>**) { /* do something */ }       else { /* do something else */ } } 

Can this be done without using reflection? How do I say IEnumerable in C#? Should I just use IEnumerable since IEnumerable<> implements IEnumerable?

like image 296
Chris Bilson Avatar asked Sep 16 '08 17:09

Chris Bilson


People also ask

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.

Is it possible to inherit from a generic type?

You can't inherit from a Generic type argument. C# is strictly typed language. All types and inheritance hierarchy must be known at compile time. . Net generics are way different from C++ templates.

How does a generic method differ from a generic type?

From the point of view of reflection, the difference between a generic type and an ordinary type is that a generic type has associated with it a set of type parameters (if it is a generic type definition) or type arguments (if it is a constructed type). A generic method differs from an ordinary method in the same way.


1 Answers

Thanks very much for this post. I wanted to provide a version of Konrad Rudolph's solution that has worked better for me. I had minor issues with that version, notably when testing if a Type is a nullable value type:

public static bool IsAssignableToGenericType(Type givenType, Type genericType) {     var interfaceTypes = givenType.GetInterfaces();      foreach (var it in interfaceTypes)     {         if (it.IsGenericType && it.GetGenericTypeDefinition() == genericType)             return true;     }      if (givenType.IsGenericType && givenType.GetGenericTypeDefinition() == genericType)         return true;      Type baseType = givenType.BaseType;     if (baseType == null) return false;      return IsAssignableToGenericType(baseType, genericType); } 
like image 73
James Fraumeni Avatar answered Oct 05 '22 23:10

James Fraumeni