开发者

Single call ternary operator

开发者 https://www.devze.com 2023-02-08 10:08 出处:网络
.NET now supports the null coalescing operator var item = aVal ?? aDefaultVal; I might be overlooking something obvious, but is t开发者_如何转开发here something similar for the ternary operator, s

.NET now supports the null coalescing operator

var item = aVal ?? aDefaultVal; 

I might be overlooking something obvious, but is t开发者_如何转开发here 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?


var item = Math.Max(5, aclass.amethod());


How about:

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

You only need to call aclass.amethod() once, then.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号