Functional programming with Linq — Enumerable.OfType

Of all the meth­ods avail­able on the Enu­mer­able class, OfType<T> is arguably one of the most use­ful and yet under uti­lized method.

For exam­ple, you have a list of Cat and Dog objects, all inher­it­ing from a com­mon Ani­mal class, but occa­sion­al­ly you want to per­form oper­a­tions on only the dogs or cats, and that’s where OfType can come in handy:

public class Animal
{
    public string Name { get; set; }
}
public class Dog : Animal {}
public class Cat : Animal {}
…

var animals = new Animal[] { new Cat { Name = "Jess" },
                             new Cat { Name = "Tad" },
                             new Dog { Name = "Bob" } };
// get the dogs from the array of animals, functional style
var dogs = animals.OfType<Dog>();

// get the cats from the array of animals, true imperative style
var cats = new List<Cat>();
foreach (var animal in animals)
{
    if (animal is Cat)
        cats.Add(animal as Cat);
}

Of course, you could equal­ly have fil­tered the array like this:

// lambda expression syntax
var cats = animals.Where(a => a is Cat).Select(a => a as Cat);
// query expression syntax
var cats = from a in animals where a is Cat select a as Cat;

But using OfType is far clean­er and expres­sive of your intent.