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>();
- The first one got an error:
"Error 1 Cannot convert type
'System.Collections.Generic.List<WindowsFormsApplication1.B>'
to'System.Collections.Generic.List<WindowsFormsApplication1.A>'
".
The second did not got an error but got
InvalidCastException
.The third one worked.
My questions are:
- Why did the first line got an error while the second line didn't?
- Why did the first two lined aren't valid?
- What's the best way to do this kind of cast? is the third line good for that or is there some better way