IEnumerable.Cast not calling cast overload

Posted by Martin Neal on Stack Overflow See other posts from Stack Overflow or by Martin Neal
Published on 2010-06-08T22:26:43Z Indexed on 2010/06/08 22:32 UTC
Read the original article Hit count: 302

Filed under:
|
|

I'm not understanding something about the way .Cast works. I have an explicit (though implicit also fails) cast defined which seems to work when I use it "regularly", but not when I try to use .Cast. Why? Here is some compilable code that demonstrates my problem.

public class Class1
{
    public string prop1 { get; set; }
    public int prop2 { get; set; }

    public static explicit operator Class2(Class1 c1)
    {
        return new Class2() { prop1 = c1.prop1, prop2 = c1.prop2 };
    }
}

public class Class2
{
    public string prop1 { get; set; }
    public int prop2 { get; set; }
}

void Main()
{
    Class1[] c1 = new Class1[] { new Class1() {prop1 = "asdf",prop2 = 1}};

    //works
    Class2 c2 = (Class2)c1[0];

    //doesn't work: Compiles, but throws at run-time
    //InvalidCastException: Unable to cast object of type 'Class1' to type 'Class2'.
    Class2 c3 = c1.Cast<Class2>().First();
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ