How-To: "Cast" between List<T>'s(devlicio.us)

submitted by dwhittakerdwhittaker(13.1k) 4 years, 11 months ago

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

2 comments |category: |Views: 24

tags: another

new Add a live kick counter to your blog >> liveImage

You can even customize the image by choosing your own colors, and then clicking the button below to update the preview and the html code:

  • "Kick It" text
  • "Kick It" background
  • kick count text
  • kick count background
  • border

Simply copy and paste this HTML into your blog post.


Users who kicked this story:
Comments:

posted by JudahGabrielJudahGabriel(814) 4 years, 11 months ago 0

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>();

Reply

posted by JudahGabrielJudahGabriel(814) 4 years, 11 months ago 0

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

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

Reply

information Login or create an account to comment on this story