sdgfsdh
sdgfsdh

Reputation: 37065

How do I pass optional arguments in extension methods?

This code does not work because I am getting options and optional arguments muddled up.

How can I pass an option to an optional argument?

type Foo() = 
  member this.Bar(?name : string, ?number : int) = 
    let name = defaultArg name "johndoe"
    let number = defaultArg number 0

    name + "-" + string number



[<AutoOpen>]
module FooExtensions = 

  open System
  
  type Foo with
    member this.Bar(?name : string, ?numberAsString : string) = 
      let number = 
        numberAsString
        |> Option.map Int32.Parse

      this.Bar(name=name, number=number) // Invalid

Upvotes: 3

Views: 75

Answers (1)

TheQuickBrownFox
TheQuickBrownFox

Reputation: 10624

You can put the question mark prefix on a named parameter when calling the method, to indicate that you want to pass a value as an option.

this.Bar(?name=name, ?number=number)

Upvotes: 3

Related Questions