I'm accessing an F# discriminated union using C# and trying to use a switch statement over the union's cases. This works fine for values that have at least one field but not for empty values as these don't have a corresponding class generated, only a property. Consider the following F# discriminated union.
type Letter = A of value:int | B of value:string | C | D
In C# I have the following switch statement inside a function that has an argument letter of type Letter:
switch (letter)
{
case A a: Console.WriteLine(a.value); break;
case B b: Console.WriteLine(b.value); break;
default:
if (letter.IsC) Console.WriteLine("C");
else if (letter.IsD) Console.WriteLine("D");
}
The default case handles the cases where the union value is empty. I'd much prefer:
switch (letter)
{
case A a: Console.WriteLine(a.value); break;
case B b: Console.WriteLine(b.value); break;
case C c: Console.WriteLine("C"); break;
case D d: Console.WriteLine("D"); break;
}
But this doesn't work because the type names C and D do not exist - C and D are properties not types. I can circumvent this by giving C and D a field of type unit but it's not very elegant. Why are types only created for non-empty discriminated union values and what's the best workaround?