Why does a Linq Cast<T> operation fail when I have an implicit cast defined?
- by Ryan Versaw
I've created two classes, with one of them having an implicit cast between them:
public class Class1
{
public int Test1;
}
public class Class2
{
public int Test2;
public static implicit operator Class1(Class2 item)
{
return new Class1{Test1 = item.Test2};
}
}
When I create a new list of one type and try to Cast<T> to the other, it fails with an InvalidCastException:
List<Class2> items = new List<Class2>{new Class2{Test2 = 9}};
foreach (Class1 item in items.Cast<Class1>())
{
Console.WriteLine(item.Test1);
}
This, however, works fine:
foreach (Class1 item in items)
{
Console.WriteLine(item.Test1);
}
Why is the implicit cast not called when using Cast<T>?