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?
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);
}
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)));
}
public static Boolean IsChildOf<T>(this Object obj)
{
// Don't forget to handle obj == null.
return obj.GetType().IsSubclassOf(typeof(T));
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With