What are the best ways to use F# Discriminated Unions from C#?
I have been digging into this problem for a while, I have probably found the simplest way, but as it is rather complex, there may be some other thing I don't see...
Having a discriminated union, e.g.:
type Shape =
| Rectangle of float * float
| Circle of float
the usage from C# I found would be (avoiding using vars, to make the type obvious):
Shape circle = Shape.NewCircle(5.0);
if (circle.IsCircle)
{
Shape.Circle c = (Shape.Circle)circle;
double radius = c.Item;
}
In C#, the NewXXXX
static methods always create object of the Shape
class, there is also a method IsXXXX
to check if the object is of the type; if and only if yes, it is castable to the Shape.XXXX
class, and only then its items are accessible; constructor of the Shape.XXXX
classes are internal, i.e. unaccessible.
Is anyone aware of a simpler option to get the data from a discriminated union?