Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerable.Cast not calling cast overload

Tags:

c#

casting

linq

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();
}
like image 796
Marty Neal Avatar asked Jun 08 '10 22:06

Marty Neal


1 Answers

The Cast<T> function works on IEnumerable, not IEnumerable<T>. As such, it's treating the instances as System.Object, not as your specific type. The explicit conversion does not exist on object, so it fails.

In order to do you method, you should use Select() instead:

Class2 c3 = c1.Select(c => (Class2)c).First();
like image 95
Reed Copsey Avatar answered Nov 19 '22 10:11

Reed Copsey