Make sure 'T' inherits or implements class / interface

Is there a way to check if T really inherits / implements a class / interface?

private void MyGenericClass<T> () { if(T ... inherits or implements some class/interface } 
+80
generics c #
May 23 '12 at 10:44
source share
8 answers

There is a method called Type.IsAssignableFrom () .

To check if T / inherits Employee :

 typeof(Employee).IsAssignableFrom(typeof(T)); 

If you are targeting .NET Core, the method has moved to TypeInfo:

 typeof(Employee).GetTypeInfo().IsAssignableFrom(typeof(T).Geβ€Œβ€‹tTypeInfo()) 
+107
May 23 '12 at 10:50
source share
β€” -

You can use class restrictions.

 MyClass<T> where T : Employee 

Take a look at http://msdn.microsoft.com/en-us/library/d5x73970.aspx

+29
May 23 '12 at 10:46
source share

If you want to check at compile time: Error, if T does NOT implement the desired interface / class, you can use the following restriction

 public void MyRestrictedMethod<T>() where T : MyInterface1, MyInterface2, MySuperClass { //Code of my method here, clean without any check for type constraints. } 

Hope this helps.

+12
Mar 27 '14 at 12:31
source share

The correct syntax

 typeof(Employee).IsAssignableFrom(typeof(T)) 

Documentation

Return value: true if c and the current Type represent the same type, or if the current Type is in the c inheritance hierarchy, or if the current Type is an interface that implements c , or if c is a parameter of the universal type and current Type represents one of the restrictions c , or if c represents the type of the value, and the current Type represents Nullable<c> ( Nullable(Of c) in Visual Basic). false if none of these conditions is true , or if c is null .

source

explanation

If Employee IsAssignableFrom T then T inherits from Employee .

Using

 typeof(T).IsAssignableFrom(typeof(Employee)) 

returns true only when either

  1. T and Employee represent the same type; or,
  2. Employee inherits from T

In some cases, this may be the intended use, but for the original question (and the more common use), to determine when T inherits or implements some class / interface , use:

 typeof(Employee).IsAssignableFrom(typeof(T)) 
+9
Jul 29 '14 at
source share

What it all really means:

 typeof(BaseType).IsAssignableFrom(typeof(DerivedType)) // => true 

because you can literally assign a BaseType instance from an instance of DerivedType :

 DerivedType childInstance = new DerivedType(); BaseType parentInstance = childInstance; // okay, assigning base from derived childInstance = (DerivedType) parentInstance; // not okay, assigning derived from base 

when

 public class BaseType {} public class DerivedType : BaseType {} 



And some specific examples if you have problems wrapping around yourself:

(via LinqPad, therefore HorizontalRun and Dump )

 void Main() { // http://stackoverflow.com/questions/10718364/check-if-t-inherits-or-implements-a-class-interface var b1 = new BaseClass1(); var c1 = new ChildClass1(); var c2 = new ChildClass2(); var nb = new nobase(); Util.HorizontalRun( "baseclass->baseclass,child1->baseclass,baseclass->child1,child2->baseclass,baseclass->child2,nobase->baseclass,baseclass->nobase", b1.IsAssignableFrom(typeof(BaseClass1)), c1.IsAssignableFrom(typeof(BaseClass1)), b1.IsAssignableFrom(typeof(ChildClass1)), c2.IsAssignableFrom(typeof(BaseClass1)), b1.IsAssignableFrom(typeof(ChildClass2)), nb.IsAssignableFrom(typeof(BaseClass1)), b1.IsAssignableFrom(typeof(nobase)) ).Dump("Results"); var results = new List<string>(); string test; test = "c1 = b1"; try { c1 = (ChildClass1) b1; results.Add(test); } catch { results.Add("FAIL: " + test); } test = "b1 = c1"; try { b1 = c1; results.Add(test); } catch { results.Add("FAIL: " + test); } test = "c2 = b1"; try { c2 = (ChildClass2) b1; results.Add(test); } catch { results.Add("FAIL: " + test); } test = "b1 = c2"; try { b1 = c2; results.Add(test); } catch { results.Add("FAIL: " + test); } results.Dump(); } // Define other methods and classes here public static class exts { public static bool IsAssignableFrom<T>(this T entity, Type baseType) { return typeof(T).IsAssignableFrom(baseType); } } class BaseClass1 { public int id; } class ChildClass1 : BaseClass1 { public string name; } class ChildClass2 : ChildClass1 { public string descr; } class nobase { public int id; public string name; public string descr; } 

results

baseclass-> BaseClass

True

child1-> BaseClass

False

baseclass-> child1

True

child2-> BaseClass

False

baseclass-> child2

True

nobase-> BaseClass

False

baseclass-> nobase

False

and

  • FAIL: c1 = b1
  • b1 = c1
  • FAIL: c2 = b1
  • b1 = c2
+7
Nov 25 '15 at 17:46
source share

I believe the syntax is: typeof(Employee).IsAssignableFrom(typeof(T));

+2
Jun 17 '14 at 20:29
source share

Although IsAssignableFrom is the best way, as others have stated, if you only need to check if the class inherits from another, typeof(T).BaseType == typeof(SomeClass) also does the job.

0
May 24 '17 at 7:28
source share

An alternative way to determine whether an object inherits an o class or implements an interface is to use the is and as operators.

If you want to know only whether the object inherits a class or implements an interface, the is operator will return a logical result:

 bool isCompatibleType = (o is BaseType || o is IInterface); 

If you want to use the inherited class or implemented interface after the test, the as operator will perform a safe cast by returning a link to the inherited class or implemented interface, if it is compatible, or zero if it is not compatible:

 BaseType b = o as BaseType; // Null if d does not inherit from BaseType. IInterface i = o as IInterface; // Null if d does not implement IInterface. 

If you only have type T , use @nikeee's answer.

0
Apr 25 '19 at 21:18
source share



All Articles