Search code examples
f#named-parameters

Invoking Record Member with Optional Parameters using Named Arguments


Consider the following record definition and accompanying method:

    type MyRecord = {
    FieldA : int
    FieldB : int
    FieldC : int option
    FieldD : int option
    } with
        static member Create(a,b,?c,?d) = {
            FieldA = a
            FieldB = b
            FieldC = c
            FieldD = d
            }

Calling the Create method as below succeeds:

    //ok
    let r1 = MyRecord.Create(1, 2)
    //ok
    let r2 = MyRecord.Create(1,2,3)

Attempting to use named parameters, either with required or optional parameters however will not compile. For example

    //Compilation fails with a message indicating Create requires four arguments
    let r2 = MyRecord.Create(FieldA = 1, FieldB =2)

According to the MSDN docs (http://msdn.microsoft.com/en-us/library/dd233213.aspx)

Named arguments are allowed only for methods, not for let-bound functions, function values, or lambda expressions.

So, based on this, I should be able to used named arguments to execute Create. Is something wrong with my syntax or am I interpreting the rules incorrectly? Is there a way to used named arguments in this context?


Solution

  • Based on your sample, I would say you have to write MyRecord.Create(a=1, b=2). Or is that a typo in your question?