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