Created
April 21, 2015 18:22
-
-
Save Kenneth-Posey/0ace3bd69a284bb2f664 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // This is proof-of-concept code for using the F# from C#, so I'm putting | |
| // the relevant snippets together in this one file | |
| // F# code | |
| namespace IntroDUs | |
| module IntroDUs = | |
| // This is a method of packing primitives into discriminated unions | |
| // and using an extension property on the DU to provide direct access | |
| // to the packed data. | |
| // You can use the packed data in the DU for strongly typed pattern matching | |
| // and other useful DU features. | |
| type FirstName = FirstName of string with | |
| member this.Value = | |
| this |> (fun (FirstName x) -> x) | |
| type LastName = LastName of string with | |
| member this.Value = | |
| this |> (fun (LastName x) -> x) | |
| type Person = { | |
| First: FirstName | |
| Last: LastName | |
| } | |
| module ExampleUse = | |
| // This creates a list of strongly typed Person records | |
| // with single case DU properties | |
| let somePeople = | |
| [ | |
| { | |
| First = FirstName "Bob" | |
| Last = LastName "Jones" | |
| } | |
| { | |
| First = FirstName "Sarah" | |
| Last = LastName "Smith" | |
| } | |
| ] | |
| // C# code | |
| using System.Linq; | |
| namespace ExampleUse | |
| { | |
| public class Example | |
| { | |
| public void ReadFromFsharp() | |
| { | |
| var bob = IntroDUs.IntroDUs.ExampleUse.somePeople.ToList()[0]; | |
| // The "value" extension property allows us to directly | |
| // access the DU values easily from C# | |
| string bobsFirstName = bob.First.Value; | |
| string bobsLastName = bob.Last.Value; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment