0

I can't share my code bu basically i have a class implementing interface like so:

public interface A
{
    void doA();
}

public class B: A
{
    public void doA()
    {
     // Doing A
    }
}

and i have a list of A like so:

List<B> list = new List<B>();
list.Add(new B());

now i want an IEnumerable<A>. so i tried these 3 lines:

List<A> listCast = (List<A>)list;
IEnumerable<A> listCastToEnumerable = (IEnumerable<A>)list;
IEnumerable<A> listCastExt = list.Cast<A>();
  1. The first one got an error:

"Error 1 Cannot convert type 'System.Collections.Generic.List<WindowsFormsApplication1.B>' to 'System.Collections.Generic.List<WindowsFormsApplication1.A>'".

  1. The second did not got an error but got InvalidCastException.

  2. The third one worked.

My questions are:

  1. Why did the first line got an error while the second line didn't?
  2. Why did the first two lined aren't valid?
  3. What's the best way to do this kind of cast? is the third line good for that or is there some better way
digEmAll
  • 56,430
  • 9
  • 115
  • 140
No Idea For Name
  • 11,411
  • 10
  • 42
  • 70

3 Answers3

1

Lets break it down.

1. Why did the first line got an error while the second line didn't?

On the second line you're casting to an IEnumerable(T) which is covariant.

2. Why did the first two lined aren't valid?

Even when you cast your List<B> it is still keeps its underlying type information which means it cannot hold items of type A which are not also of type B.

3. What's the best way to do this kind of cast? is the third line good for that or is there some better way

The third line casts each element of the List into type A and return a new IEnumerable(T) of type A. This can be iterated into a new List of type A which will happily hold any element of type A.

Dustin Kingen
  • 20,677
  • 7
  • 52
  • 92
0

You can also do

 IEnumerable<A> listoftypeb = list.OfType<A>();

This will give you a list of A without an error if you have an element that can't be case to type A

Hogan
  • 69,564
  • 10
  • 76
  • 117
0

you need to create an IEnumerable(T) and populate it with your data from your list, because List<B> is not IEnumerable<A>