Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# AND operator with null checking

Tags:

operators

c#

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
}
like image 538
Eadel Avatar asked Oct 12 '12 09:10

Eadel


People also ask

What is C full form?

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.

What C is used for?

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 ...

What is C language?

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.

Why is C named so?

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'.


2 Answers

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.

like image 177
Raphaël Althaus Avatar answered Sep 29 '22 10:09

Raphaël Althaus


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.

like image 21
RB. Avatar answered Sep 29 '22 10:09

RB.