Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FSharpChoice in C#

Tags:

c#

f#

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?

like image 832
Pradeep Avatar asked Feb 23 '11 12:02

Pradeep


2 Answers

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).

like image 135
Tomas Petricek Avatar answered Sep 21 '22 09:09

Tomas Petricek


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.

like image 39
kvb Avatar answered Sep 21 '22 09:09

kvb