Say, we have 2 classes:
public class A
{
public int a;
}
public class B
{
public int b;
public static implicit operator B(A x)
{
return new B { b = x.a };
}
}
Then why
A a = new A { a = 0 };
B b = a; //OK
List<A> listA = new List<A> { new A { a = 0 } };
List<B> listB = listA.Cast<B>().ToList(); //throws InvalidCastException
The same for explicit operator.
P.S.: casting each element manually (separetely) works
List<B> listB = listA.Select<A, B>(s => s).ToList(); //OK
The name of
Enumerable.Castis misleading as its purpose is to unbox values. It works onIEnumerable(not onIEnumerable<T>) to produce anIEnumerable<T>. If you already have anIEnumerable<T>Enumerable.Castis most likely not the method you want to use.Technically, it is doing something like this:
If
Tis something else than the boxed value, this will lead to anInvalidCastException.You can test this behaviour yourself:
You have two possible solutions:
Select(x => (B)x)Castthat works on anIEnumerable<T>rather than anIEnumerable.