Monday, May 4, 2009

LINQ's OfType and Inheritance

Just in case you were wondering, the generic type argument passed into the LINQ method "OfType<T>" filters the list to only objects that are, or inherit from a specific type, that is, it will also return instances of objects that inherit from the specified type. The following code gives an example:


public class Thing 
{
public override string ToString()
{
return "I'm a CompanyBase";
}
}

public class Widget : Thing
{
public override string ToString()
{
return "I'm a WidgetBase";
}
}

public class FooWidget : Widget
{
public override string ToString()
{
return "I'm a FooWidget";
}
}

public class BarWidget : Widget
{
public override string ToString()
{
return "I'm a BarWidget";
}
}


public class Gadget : Thing
{
public override string ToString()
{
return "I'm a Gadget!";
}
}

class Program
{
static void Main(string[] args)
{
List<Thing> items = new List<Thing>();
items.Add(new Gadget());
items.Add(new Thing());
items.Add(new Widget());
items.Add(new FooWidget());
items.Add(new BarWidget());

var widgets = items.OfType<Widget>();

foreach (var item in widgets)
Console.WriteLine(item);
Console.ReadLine();
}
}