Search code examples
c#.netprogramming-languages

Single call ternary operator


.NET now supports the null coalescing operator

var item = aVal ?? aDefaultVal; 

I might be overlooking something obvious, but is there something similar for the ternary operator, such that instead of doing

var item = aclass.amethod() > 5 ? aclass.amethod() : 5; 

it wouldn't be needed to call amethod() twice?


Solution

  • There is no such operator built into C#.

    While I would select one of the other answers (the one that uses Math.Max is arguably more clear for the example posted), this is here just to show another method. It's a shame that the computation requires an explicitly-typed variable.

    Func<int,int> computation = (x) => x > 5 ? x : 5;
    var item = computation(aclass.amethod());
    

    And in-line, which is just ugly in C#.

    var item = ((Func<int,int>)((x) => x > 5 ? x : 5))(aclass.amethod());
    

    Of course both of the above really boil down to just:

    var item = DoComputation(aclass.amethod());
    

    And utilize the fact that C# does not use pass-by-name :-)

    Or, perhaps an extension method:

    static class Ext {
      public static TO Apply<TI,TO> (this TI obj, Func<TI,TO> fn) {
        return fn(obj);
      }
    }
    
    // note C# now lets us get away with no explicit Func<...> type
    var item = Ext.Apply(aclass.amethod(), x => x > 5 ? x : 5);
    
    // or as extension method -- imagine computation is as it was in the
    // first example, or a compatible method group
    var item = aclass.amethod().Apply(computation);
    

    Happy coding.