C#/.NET Little Wonders: Use Cast() and TypeOf() to Change Sequence Typ

added by BlackRabbitCoder
6/8/2012 8:55:49 AM


We’ve seen how the Select() extension method lets you project a sequence from one type to a new type which is handy for getting just parts of items, or building new items. But what happens when the items in the sequence are already the type you want, but the sequence itself is typed to an interface or super-type instead of the sub-type you need? For example, you may have a sequence of Rectangle stored in an IEnumerable<Shape> and want to consider it an IEnumerable<Rectangle> sequence instead. Today we’ll look at two handy extension methods, Cast<TResult>() and OfType<TResult>() which help you with this task.


6/7/2012 6:05:44 PM
new post