Quick reminder about the workings of Type.IsAssignableFrom

Here is a quick reminder about the workings of Type.IsAssignableFrom:

class Fruit {}
class Banana : Fruit {}

[Test]
public void CanAssignBananaToFruit()
{
 var fruit = typeof (Fruit);
 var banana = typeof (Banana);
 Assert.IsTrue(fruit.IsAssignableFrom(banana));
}

[Test]
public void CanNotAssignFruitToBanana()
{
 var fruit = typeof(Fruit);
 var banana = typeof(Banana);
 Assert.IsFalse(banana.IsAssignableFrom(fruit));
}

I really hate this API because it always seems backward to me. Here is how i really want to use it:

Assert.IsTrue(banana.CanBeAssignedTo(fruit));
Assert.IsFalse(fruit.CanBeAssignedTo(banana));

With the aid of an extension method we can easily achieve this:

public static bool CanBeAssignedTo(this Type sourceType, Type destinationType)
{
 return destinationType.IsAssignableFrom(sourceType);
}

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>