How do I create a member that has an out parameter in F#
clr, f#
Solution
No, you can't return the result as a tuple -- you need to assign the value to the byref value before returning the result from the function. Also note the `[<Out>]` attribute -- if you leave that out, the parameter acts like a C# `ref` parameter.
open System.Runtime.InteropServices
type Foo () =
static member TryParse (str : string, [<Out>] success : byref<bool>) : Foo =
// Manually assign the 'success' value before returning
success <- false
// Return some result value
// TODO
raise <| System.NotImplementedException "Foo.TryParse"
If you want your method to have a canonical C# `Try` signature (e.g., `Int32.TryParse`), you should return a `bool` from your method and pass the possibly-parsed `Foo` back through the `byref<'T>`, like so:
open System.Runtime.InteropServices
type Foo () =
static member TryParse (str : string, [<Out>] result : byref<Foo>) : bool =
// Try to parse the Foo from the string
// If successful, assign the parsed Foo to 'result'
// TODO
// Return a bool indicating whether parsing was successful.
// TODO
raise <| System.NotImplementedException "Foo.TryParse"
Problem
I know that in f# I can treat `out` parameters as members of a result tuple when I'm using them from F#, e.g. ``` (success, i) = System.Int32.TryParse(myStr) ``` What I'd like to know is how I define a member to have signature that appears to C# as having an `out` parameter. Is it possible to do this? And can I just return a tuple and have the opposite process occur when I call the method from C#, e.g. ``` type Example() = member x.TryParse(s: string, success: bool byref) = (false, Unchecked.defaultof<Example>) ```