csharp-light

FSharp · Script

/Program.fs

open System

// =================================
// C# light
// =================================

type Person(name :string, birthday :DateTime) =

    /// Full name
    member this.Name = name 

    /// Birthday
    member this.Birthday = birthday
    
    
// =================================
// DTO Example    
// =================================

// I have renamed Person!
type Person2 = {name :string; birthday :DateTime}

let person = {name="Alice"; birthday=DateTime.Today}    



// =================================
// Automatically generate code for equality
// =================================


let alice1 = {name="Alice"; birthday=DateTime.Today}
let alice2 = {name="Alice"; birthday=DateTime.Today}

if alice1 = alice2 then
    Console.WriteLine("Alice1 and Alice2 are equal")  // true!
    
    
// =================================
// Immutability    
// =================================

//define an immutable Alice 
let alice3 = {name="Alice"; birthday=DateTime.Today}

//changing immutable Alice to Bob gives an error
// alice3 <- {name="Bob"; birthday=DateTime.Today}  // This value is not mutable

//define a mutable Alice 
let mutable alice4 = {name="Alice"; birthday=DateTime.Today}

//changing mutable Alice to Bob is ok
alice4 <- {name="Bob"; birthday=DateTime.Today}
Console.WriteLine("Alice's name is " + alice4.name)

// =================================
// Non-null reference classes
// =================================

// alice4 <- null  // error
                   // The type 'Person' does not have 'null' as a proper value
                   

// =================================
// Allow anonymous types to implement interfaces                   
// =================================

do 
    // create it
    use tempDisposable = 
      {new IDisposable with 
        member this.Dispose() = Console.WriteLine("Disposed") }

    // do something             
    Console.WriteLine("Doing something") 
    
    // tempDisposable goes out of scope and is disposed
    

// =================================
// Allow subclasses to be merged into a single "case" class
// =================================

type CheckNo = int
type CardType = Visa | Mastercard
type CardNo = string

type PaymentMethod = 
| Cash
| Check of CheckNo
| Card of CardType * CardNo  


let cash = Cash
let check = Check 123
let card = Card (Visa, "4012888888881881")

let printPayment payment =   
   match payment with
   | Cash -> printfn "Cash"
   | Check checkNo -> printfn "Check %i" checkNo
   | Card (cardType,cardNo) -> printfn "Card %A %s" cardType cardNo
   
printPayment cash
printPayment check
printPayment card
;