C # AND operator with zero validation

I read that the AND && operator in .NET conditionally evaluates its second argument.

Is it safe to check for null and then check for any field inside the same statement?

For example, imagine that we have a class SomeClass that has an integer field Id:

 class SomeClass { public Int32 Id { get; set; } } 

Then we get an object of this type somewhere and try to perform some actions on it:

 public void SomeMethod(SomeClass obj) { if (obj != null) if (obj.Id == 1) { // do some actions } } 

Is it possible to rewrite this as follows to reduce the amount of code? Will checking for zero be safe?

 public void SomeMethod(SomeClass obj) { if (obj != null && obj.Id == 1) // do some actions } 
+6
source share
5 answers

Yes, it will be safe, && conditions are processed "from left to right", if the first does not match in your case, the second will not be evaluated

msdn

Operation

x && y

corresponds to operation

x and y

, except that if x is false, y is not evaluated because the result of the AND operation is false regardless of the value of y. This is known as a "short circuit" rating.

+7
source

Yes, it is absolutely safe.

As you state in your question, if an object is null, only the first condition is evaluated, so the second condition (which raises a NullReferenceException) is never fulfilled. This is also known as a short circuit.

+3
source

Yes ... It is safe in C # and many other languages. If the program knows that the following checks cannot make the if statement true, there is no need to even look at them.

This type of assessment is called Lazy Evaluation .

+1
source

The term here is “short circuit” . When using the operator (&&) , if the first condition is not met, it will not continue with the following condition. They, as you do, not only save, this is the right way to do it.

7.11 Conditional Logical Operators - C # MSDN Link

& & and || operators are called conditional logical operators. They are also called "short-circuited" logical operators.

+1
source

yes, this is simple logic, if among several AND indices one is false, there is no need to continue evaluating them, because the result will be FALSE, so the compiler stops evaluating when it detects the first FALSE

+1
source

Source: https://habr.com/ru/post/927546/


All Articles