Why does a Linq Cast<T> operation fail when I have an implicit cast defined?

Posted by Ryan Versaw on Stack Overflow See other posts from Stack Overflow or by Ryan Versaw
Published on 2009-04-30T19:51:50Z Indexed on 2010/05/15 23:50 UTC
Read the original article Hit count: 185

Filed under:
|
|

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>?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about LINQ