I am trying to use FSharpChoice
type in a C# project. I have created a choice like so
var a = FSharpChoice<T1,T2,T3>.NewChoice1Of3(instofT1);
now how do I get instofT1
out of the choice type.
I see I can do a IsChoice1Of3
but how do i get to the value in the choice object?
I probably wouldn't use the type directly from C# - you can do that, but the resulting code won't be very nice. I'd probably declare my own Choice
type that would look like this:
type Choice<'T1, 'T2> private (opt1, opt2) =
member x.TryGetChoice1Of2(arg:byref<'T1>) = //'
match opt1 with
| Some v -> arg <- v; true
| _ -> false
// Similar code for 'TryGetChoice2Of2'
type Choice = // static methods for creating (Choice1Of2, ...)
This uses byref
parameters which appear as out
parameters in C#, so you could write:
int num;
string str;
if (choice.TryGetChoice1Of2(out num)) // ...
else if (choice.TryGetChoice2Of2(out str)) // ...
else // assert(false)
This is definitely more pleasant way of working with the type from C# (and it uses pattern familiar from, for example, working with Int32.TryParse
).
Cast the value to FSharpChoice<T1,T2,T3>.Choice1Of3
and use the Item
property.
See Compiled Form of Union Types for Use from Other CLI Languages in the F# spec for more information about how discriminated unions are represented.
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