What is happening in an “If(..||..)” and “If(…&&…)” construct internally?

后端 未结 6 1990
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-15 18:29

I was just wondering what happens inside of an \"if OR\" and \"if AND\". I have a feeling that it\'s just syntactic sugar to use &

6条回答
  •  心在旅途
    2020-12-15 18:55

    Their VB equivalents can be more describing. || is OrElse and && is AndAlso in VB.
    These are conditional operators; meaning they make the control clause - if in your case - evaluate the conditions as needed and not all of them always.

    For example, in if ( a || b ) if a is true, it doesn't matter what b is; the result is true and therefore b will not get evaluated and this will result in faster execution.

    This feature can be used as a null-checking mechanism too. if ( a != null && a.prop == somevalue ) will prevent a Null Reference Exception if a is null and if it's not null, its prop property will be accessed to evaluate the second condition.

提交回复
热议问题