Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if two generic types are equal

Tags:

c#

types

generics

I need to find if a type is a certain generic type.

class MyType<T> {}
var instance = new MyType<int>();
var type = instance.GetType();

This check does not work, but this is what I want to check. If the type is of that generic type, regardless of what T is.

type == typeof( MyType<> )

This does work, but feels dirty. It could also be wrong since it's not the FullName.

type.Name == typeof( MyType<> ).Name

I'm assuming there is a way to do this, but I haven't found one. Using IsAssignableFrom will not work, because I need to know if the current type, and not one of it's parents, are equal.

like image 610
Josh Close Avatar asked May 02 '13 02:05

Josh Close


1 Answers

This will work if the concrete type of the object is MyType<T>. It will not work for instances of types derived from MyType<T>, and will not work if MyType<T> is an interface type.

if (type.IsGenericType
    && type.GetGenericTypeDefinition() == typeof(MyType<>))
like image 56
Sam Harwell Avatar answered Nov 10 '22 19:11

Sam Harwell