C#. Do if( a == (b or c or d)). Is it possible?

前端 未结 11 1625
无人及你
无人及你 2021-02-02 09:31

Is there another way to write something like this:

if (a == x || a == y || a == z)

One way that I found is doing it like this:

         


        
11条回答
  •  清酒与你
    2021-02-02 10:11

    Consider a case where a == x, and y and z are slow-to-evaluate, expensive functions.

    • In if(a == x || a == y || a == z) you have the benefit of the short-circuit ||-operator, so you y and z won't be evaluated.
    • If you make an array with new[] { x, y, z } - y and z will be evaluated every time.

    The 'trick' with .Contains() would be more useful if there was an elegant syntax to create lazy-evaluated sequence (IEnumerable). i.e. something like yield return x; yield return y;..., but inlined and shorter.

提交回复
热议问题