Pages

Monday, October 1, 2012

F# and C# optional parameter

F# optional parameter is defined like:

namespace MyClassNamespace

type MyClass() =
    member this.PrintValue(?value:int) =
        match value with
            | Some(n) -> printfn "value is %A" n
            | None -> printfn "sorry, no value"

the C# code invoke the F# code is like:

static void Main(string[] args)
{
    var myValue = new MyClassNamespace.MyClass();

    myValue.PrintValue(Microsoft.FSharp.Core.FSharpOption< int >.None);
    myValue.PrintValue(new Microsoft.FSharp.Core.FSharpOption< int >(1));
}

The C# side code is not that nice.

If you prefer the C# side does not need to reference to FSharp.Core.dll. The the Optional and DefaultParameterValue is your friend. :)

namespace MyClassNamespace

open System.Runtime.InteropServices

type MyClass() =
    member this.PrintValue(?value:int) =
        match value with
            | Some(n) -> printfn "value is %A" n
            | None -> printfn "sorry, no value"

    member this.PrintValue2([< Optional;DefaultParameterValue(0) >]value:int,
                            [< Optional;DefaultParameterValue(null) >]str:string) =        
        let defaultStr = if str = null then "null value" else str
        printfn "(%A, %A)" value defaultStr

The F# side invoke C# optional code is fairly easy.

public class CSharpClass
{
    public void MyMethod(int a = 11)
    {
        Console.WriteLine("a = {0}", a);
    }
}

let c = ConsoleApplication1.CSharpClass()

c.MyMethod()
c.MyMethod(100)
c.MyMethod(a=199)




No comments: