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);
}