Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension method to check if an object is sub class of T

Tags:

c#

.net

.net-4.5

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

Here is what I did, but not accepted by 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 can i write this?

like image 970
Maro Avatar asked Apr 25 '14 22:04

Maro


4 Answers

You can just use is. But note that is doesn't do exactly the same as IsSubclassOf. See Jeppe's excellent comment for details and I have an example below too.

On a side note, I don't think Java allows the equivalent instanceof in such a generic case for some reason, but it's OK in C#. I.e.:

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

Then this makes it so trivial that it's more confusing to readers to use an extension method than is directly. If you used it directly your test would then look like:

[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);
}
like image 52
weston Avatar answered Nov 03 '22 03:11

weston


Use GetType instead of typeof when you have an instance of the type:

public static bool IsChildOf<T>(this object obj)
{
    return (obj.GetType().IsSubclassOf(typeof(T)));
}
like image 26
McGarnagle Avatar answered Nov 03 '22 05:11

McGarnagle


public static Boolean IsChildOf<T>(this Object obj)
{
   // Don't forget to handle obj == null.
   return obj.GetType().IsSubclassOf(typeof(T));
}
like image 5
Daniel Brückner Avatar answered Nov 03 '22 05:11

Daniel Brückner


public static bool IsChildOf<T>(this object obj)
    {
        return obj != null && (obj.GetType().IsSubclassOf(typeof(T)));
    }

also use Assert.IsTrue in place of Assert.That

like image 2
Tim V.H Avatar answered Nov 03 '22 05:11

Tim V.H