Monthly Archives: October 2012

Type check and inheritance – and a nice ReSharper tip

Let’s suppose you have three classes in a simple hierarchy :

public class A
{
}

public class B : A
{
}

public class C : A
{
}

Now suppose you receive an instance of one of these classes (you don’t know the exact type to which this instance belongs). How can you determine programatically if the instance is of a type inheriting from A or it is of type A exactly?

Normally I would do the following :

var instance = ObtainInstanceFromSomeWhere(); // this method will not return null
var instanceIsExactlyOfTypeA = typeof(A) == instance.GetType();
var instanceIsOfTypeAOrAnInheritingType = typeof(A).IsAssignableFrom(instance.GetType());

All these work and are nice and dandy. However ReSharper showed me a nicer alternative to the last statement :

var instanceIsOfTypeAOrAnInheritingType = typeof(A).IsInstanceOfType(instance);

Now, pro’lly, many of you knew about this method but I didn’t! :)
Hopefully it will help someone..

WP Like Button Plugin by Free WordPress Templates