Check if two common types are equal

I need to find if a type is a specific 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 of this generic type, regardless of what T

 type == typeof( MyType<> ) 

It works, but it feels dirty. This may also be incorrect, as it is not a FullName .

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

I guess there is a way to do this, but I have not found it. Using IsAssignableFrom will not work, because I need to know if the current type is equal and not one of the parents.

+6
source share
1 answer

This will work if the specific object type 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<>)) 
+6
source

Source: https://habr.com/ru/post/944087/


All Articles