Do nothing when “other side” of ternary operator is reached?

后端 未结 5 1800
醉酒成梦
醉酒成梦 2021-01-12 01:43

Note: I\'ve seen this question asked sometimes before (a, b, c), but neither of these was in C#, nor helpful.

Assume I\'m using the ? : ternary

5条回答
  •  心在旅途
    2021-01-12 02:42

    I can suggest an extension method like this:

    public static T ChangeOn(this T variable, bool condition, T newValue)
    {
        return condition ? newValue : variable;
    }
    

    And use it like this:

    var result = r.ChangeOn(r == 5, 0);
    //or: r = r.ChangeOn(r == 5, 0); for self change
    

提交回复
热议问题