I read that the AND operator &&
in .NET conditionally evaluates its second argument.
Is it safe to check for null and then check some field within a single statement?
For example, imagine we have a class SomeClass, which has an integer field Id:
class SomeClass
{
public Int32 Id { get; set; }
}
Then, we receive 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
}
}
Can we rewrite this as follows to reduce the amount of code? Will the null-check be safe?
public void SomeMethod(SomeClass obj)
{
if (obj != null && obj.Id == 1)
// do some actions
}
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
C is an imperative procedural language supporting structured programming, lexical variable scope, and recursion, with a static type system. It was designed to be compiled to provide low-level access to memory and language constructs that map efficiently to machine instructions, all with minimal runtime support.
After language 'B', Dennis Ritchie came up with another language which was based upon 'B'. As in alphabets B is followed by C and hence he called this language as 'C'.
Yes it will be safe, && conditions are treated from "left to right", if the first doesn't match in your case, the second won't be evaluated
msdn
The operation
x && y
corresponds to the operation
x & y
except that if x is false, y is not evaluated, because the result of the AND operation is false no matter what the value of y is. This is known as "short-circuit" evaluation.
Yes, that is absolutely safe to do.
As you state in your question, if the object is null, only the first condition is evaluated, so the second condition (which would raise a NullReferenceException) is never executed. This is known also as "short-circuit" evalation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With