2

I have a C# Class with a method with several optional parameters that throws exceptions. I'd like to catch the exceptions and return a result while maintaining the ability to supply optional arguments. Is there a way to do this with multiple optional parameters without creating huge amounts of cases in a match expression?

type SomeType with
    member this.DoSomethingResult(?a, ?b:, ?c) =
            try
                let x =
                    match a, b, c with
                    | None, None, None -> this.DoSomething()
                    | Some a, None, None -> this.DoSomething(a)
                    | Some a, Some b, None -> this.DoSomething(a, b)
                    | Some a, None, Some c -> this.DoSomething(a, c = c)
                    | Some a, Some b, Some c -> this.DoSomething(a, b, c)
                    | None, Some b, None -> this.DoSomething(b = b)
                    | None, Some b, Some c -> this.DoSomething(b = b, c = c)
                    | None, None, Some c -> this.DoSomething(c = c)

                Ok x
            with ex -> Error ex.Message

The number of cases is proportional to the factorial of the number of parameters so this is clearly not a feasible pattern for more than 3 parameters and even that is pushing it. I thought about using defaultArg and only calling the inner method with all parameters but I don't necessarily know what the defaults are for the wrapped method (or if there is a way to extract them) and don't want to alter the default behaviour.

tranquillity
  • 1,619
  • 1
  • 5
  • 12

1 Answers1

2

This answer provided a hint to the solution but I couldn't find a question that specifically addressed this problem. The trick is the use of optional named parameters in the inner method call:

type SomeType with
    member this.DoSomethingResult(?a, ?b:, ?c) =
            try
                let x = this.DoSomething(?a = a, ?b = b, ?c = c)
                Ok x
            with ex -> Error ex.Message

After finding the solution the relevant Microsoft docs were also easy to locate.

tranquillity
  • 1,619
  • 1
  • 5
  • 12