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();
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With