What is the simplest way to access data of an F# discriminated union type in C#?

前端 未结 7 1219
耶瑟儿~
耶瑟儿~ 2020-12-10 01:23

I\'m trying to understand how well C# and F# can play together. I\'ve taken some code from the F# for Fun & Profit blog which performs basic validation returning a discr

相关标签:
7条回答
  • 2020-12-10 01:58

    How about this? It's inspired by @Mauricio Scheffer's comment above and the CSharpCompat code in FSharpx.

    C#:

    MyUnion u = CallIntoFSharpCode();
    string s = u.Match(
      ifFoo: () => "Foo!",
      ifBar: (b) => $"Bar {b}!");
    

    F#:

      type MyUnion =
        | Foo
        | Bar of int
      with
        member x.Match (ifFoo: System.Func<_>, ifBar: System.Func<_,_>) =
          match x with
          | Foo -> ifFoo.Invoke()
          | Bar b -> ifBar.Invoke(b)
    

    What I like best about this is that it removes the possibility of a runtime error. You no longer have a bogus default case to code, and when the F# type changes (e.g. adding a case) the C# code will fail to compile.

    0 讨论(0)
提交回复
热议问题