Working with logical AND (&&) and OR(||) operators, in most situations we use the short-circuiting versions of conditional operators (&&,||). Short-circuiting effectively means that if the overall logical result has already been determined, then the remainder of the logical expression is not even evaluated.
See the following example,
1
2
3
4
5
6
7
8
9
10
11
|
[TestMethod]
public void ShortCircuting()
{
bool defaultValue = false ;
bool result = defaultValue && ReturnBoolean();
return ;
}
public bool ReturnBoolean()
{
return true ;
}
|
So, our first logical expression was saying defaultValue equals false. So, the outcome of this will of course be false because we’ve just got a hard-coded false value here. But what’s interesting here is that because the overall outcome of the logical expression has already been determined here. So remainder of the logical expression is not even evaluated, and we can see this in action in this next statement. I’ll go and put a breakpoint here, and I’ll step into the statement. And notice that we didn’t even enter the ReturnBoolean method.
If we don’t want this short-circuiting behavior, we can use the non short-circuiting Conditional (&,|) operator. So, if we step into this now, we can see that our ReturnBoolean method has now been executing even though we’ve got a false here.
1
2
3
4
5
6
7
8
9
10
11
|
[TestMethod]
public void NonShortCircuting()
{
bool defaultValue = false ;
bool isTrue = defaultValue & ReturnBoolean();
return ;
}
public bool ReturnBoolean()
{
return true ;
}
|