Search code examples
f#return-valuepipelineinfix-notationinfix-operator

Is it possible to use the pipeline operator to call a method on a returned object?


Is it possible to call a method on a returned object using the pipeline infix operator?

Example, I have a .Net class (Class1) with a method (Method1). I can currently code it like this:

let myclass = new Class1()
let val = myclass.Method1()

I know I could also code it as such

let val = new Class1().Method1()

However I would like to do be able to pipeline it (I am using the ? below where I don't know what to do):

new Class1()
|> ?.Method1()

Furthermore, say I had a method which returns an object, and I want to only reference it if that method didn't return null (otherwise bail?)

new Class1()
|> ?.Method1()
|> ?? ?.Method2()

Or to make it clearer, here is some C# code:

    public void foo()
    {
        var myclass = new Class1();
        Class2 class2 = myclass.Method1();
        if (class2 == null)
        {
            return;
        }
        class2.Method2();
    }

Solution

  • You can define something similar to your (??) operator fairly easily (but operators can't start with a question mark):

    let (~??) f x =
      if (x <> null) then
        f x
    

    Unfortunately, your pipelined code will need to be a bit more verbose (also, note that you can drop the new keyword for calling constructors):

    Class1()
    |> fun x -> x.Method1()
    

    Putting it all together:

    Class1()
    |> fun x -> x.Method1()
    |> ~?? (fun x -> x.Method2())