Friday November 27th

Thursday November 26th

Wednesday November 25th

How-To: "Cast" between List<T>'s

If you've ever tried to cast been list generics, you know that you can't.


I find using a generic method for this a lot easier:

public IEnumerable<TBase> As<TBase, TDerived>(IEnumerable<TDerived> derived)
where TDerived : TBase
foreach(TDerived item in derived) yield return item;

You call it like this:

// C# 2
IEnumerable<Square> mySquares = ...;
IEnumerable<Shape> myShapes = As<Shape, Square>(mySquares);

// C# 3 with extension methods would make it a little more natural:
IEnumerable<Shape> myShapes = mySquares.As<Shape>();

Oh, and if you need to create a list from that, it's as simple as saying

List<Shape> shapes = new List<Shape>(myShapes);

Commenting on Stories is limited for now and will open up to those recommended by the community. Learn how
Loading DotNetKicks...
brought to you by the Kicks Network