Extension method to check if an object is a subclass of T

I am trying to write an extension method that checks if an object is a subclass of T.

Here is what I did, but did not accept the visual studio.

public static bool IsChildOf<T>(this object obj) { return (typeof(obj).IsSubclassOf(typeof(T))); } [Test()] public void IsChildOfTest() { var dog = new Dog(); var isAnimal = dog.IsChildOf<Animal>(); Assert.That(isAnimal); } 

Any idea how I can write this?

+6
source share
4 answers

You can just use is . But note that is does not do the same as IsSubclassOf . See Jeppe for a great comment for details, and I also have an example below.

On the side of the note, I donโ€™t think Java allows the equivalent of instanceof in this general case for some reason, but this is normal in C #. I.e:.

 public static bool IsChildOf<T>(this object obj) { return obj is T; } 

Then this makes it so trivial that it is more confusing for readers to use the extension method than is directly. If you used it directly, your test will look like this:

 [Test()] public void IsChildOfTest() { var dog = new Dog(); var isAnimal = dog is Animal; Assert.That(isAnimal); } 

An example of one of the differences between is and IsSubclassOf :

 [Test] public void IsChildOfTest() { var dog = new Dog(); Assert.False(dog.GetType().IsSubclassOf(typeof(Dog))); Assert.True(dog is Dog); } 
+6
source

Use GetType instead of typeof if you have an instance of type:

 public static bool IsChildOf<T>(this object obj) { return (obj.GetType().IsSubclassOf(typeof(T))); } 
+6
source
 public static Boolean IsChildOf<T>(this Object obj) { // Don't forget to handle obj == null. return obj.GetType().IsSubclassOf(typeof(T)); } 
+5
source
 public static bool IsChildOf<T>(this object obj) { return obj != null && (obj.GetType().IsSubclassOf(typeof(T))); } 

also use Assert.IsTrue instead of Assert.That

+2
source

All Articles