Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

c# - What happens if the first part of an if-structure is false?

I was wondering what happens when a program processes an if-structure with multiple conditions. I have an idea, but I'm not sure about it. I'll give an example:

List<string> myTestList = null;
if (myTestList != null && myTestList.Count > 0)
{
    //process
}

The list is null. When processing the if statement, will it go from left to right exiting the if as soon as one condition is false?

I've tried it and seems to throw no errors, so I assume the above explains it, but I'm not sure.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is the && that is important. This is short-circuiting, so the Count is never evaluated; The conditions are evaluated left-to-right.

There is also a non-short-circuiting operator (&), but it is very rare to see in an if test; it is mainly intended for bitwise operations (on int etc).

From the spec:

Conditional logical operators

The && and || operators are called the conditional logical operators. They are also called the “short-circuiting” logical operators.

...

The && and || operators are conditional versions of the & and | operators:

  • The operation x && y corresponds to the operation x & y, except that y is evaluated only if x is not false.
  • The operation x || y corresponds to the operation x | y, except that y is evaluated only if x is not true.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...