Search code examples
c#exceptionvaluetuple

Ienumerable.cast to ValueTuple InvalidCastException


I have this class named Point2D having two properties X and Y. This class has an implicit conversion to ValueTuple (double x, double y)

My problem comes when I cast List<Point2D>() to List<(double x, double y)>() using Linq Ienumerable.Cast<T>(), it gives me InvalidCastException

What am I doing wrong?

Edit:

Example

public class Point2D
{
public Point2D(double x, double y)
{X=x;
Y=y;
}
 public double X {get;}
public double Y {get;}

public static implicit operator (double x, double y) (Point2D point)=> (point.X, point.Y);

public static implicit operator Point2D((double x, double y) point) => new Point2D( point.x, point.y);
}

There's the class, so if I do this

var points=new List<Point2D>(){(1,2),(2,3)};

I get cast exception if I do this

var list = points.Cast<(double x, double y)>().ToList();

Solution

  • When you are defining your operators, you are defining custom conversion operators, not cast operators. Custom conversion operators are only applied at compile time from one static type to another (which generally means they can't be used in generic methods). The "Cast" enumerable method is only applying cast operations (as the name implies).

    It's not possible to create custom casting operators (casting is a thing only the language/runtime can mess around with).

    If you change points.Cast<(double x, double y)>() to points.Select>(p => ((double x, double y))p), that will instead invoke your custom cast operator (though it looks pretty crazy with all those parenthesis, but the are needed to convert to the named tuple).