Nested if statements

I hope this is no longer asked.

I have a nullable boolean called boolIsAllowed and an if condition like this:

if(boolIsAllowed.HasValue && boolIsAllowed.Value) { //do something } 

My question is this good code, or would I rather split it into a nested if statement? Will the second condition be checked if boolIsAllowed.HasValue is false and then throws an exception?

Hope this question is not too stupid.

Thanks in advance.

+6
c # if-statement
source share
7 answers

Itโ€™s good as it is. The second condition will not be checked if HasValue false, so it will not throw an exception. It is somehow:

 string name = ...; if (name != null && name.Length > 5) 

Again, this is fine - you will not get a NullReferenceException if name is null because && is short-circuited.

Similar to || the operator has a short circuit, but vice versa: there, if the left operand is true, the general expression evaluates to true without checking the right operand. For example:

 // Treat null as if it were an empty string if (name == null || name.Length == 0) 

EDIT: As noted in the comments, this only applies to && and || - this does not apply to and and |, which always evaluate both operands.

+18
source share

You can check the true value even if it is null:

 bool? val = null; if( val == true ) // Works { //do something } 
+8
source share

What about:

 if (boolIsAllowed ?? false) { } 
+6
source share

More generally, if your if statement has several conditions, consider extracting them to a method. This is not necessary in this particular case, as some of the other answers have shown. But in more complex cases, it can be much simpler. Would you rather support:

 if (taxApplied && taxValue > minimumTax && customerIsPreferred) { // Do something } 

or

 if (CustomerGetsTaxRebate()) { // Do Something } 
+1
source share

you can just do this:

 if(boolIsAllowed.GetValueOrDefault(false)) { } 

But your source code will not throw an exception, because if the first test failed, then the whole test runs up because && is ', as well as', so if the first test is false, then there is no way to run the test.

0
source share

The second operand is evaluated only if the first operand is true. There is no need to insert if .

0
source share

You are doing it safely. C # short circuit of boolean expressions, here's why:

if (list! = null && list.Count> 0)

Working. The code will not try to evaluate the second condition, because it knows that it cannot be true, since the first result was false.

Not all languages โ€‹โ€‹do this, they do a lot. In VB.NET, you must do this explicitly with OrElse and AndAlso.

0
source share

All Articles