Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine whether object reference is null?

What is the best way to determine whether an object reference variable is null?

Is it the following?

MyObject myObjVar = null;
if (myObjVar == null)
{
    // do stuff
}
like image 664
CJ7 Avatar asked Aug 17 '12 05:08

CJ7


People also ask

How do you check if an object reference is null?

isNull() Method to Check if Object Is Null in Java When you pass a reference of an object to the isNull() method, it returns a boolean value. It returns true if the reference is null, otherwise, it returns false. The definition of the isNull() method is given below. Let us see the example in code.

Can an object reference be null?

One of the main causes of bugs with null reference is the fact that in C every reference type object can be null, all the time.

Is null an object in C#?

null (C# Reference)The null keyword is a literal that represents a null reference, one that does not refer to any object. null is the default value of reference-type variables.


2 Answers

You can use Object.ReferenceEquals

if (Object.ReferenceEquals(null, myObjVar)) 
{
   ....... 
} 

This would return true, if the myObjVar is null.

like image 152
Mohan Avatar answered Sep 22 '22 11:09

Mohan


The way you are doing is the best way

if (myObjVar == null)
{
    // do stuff
}

but you can use null-coalescing operator ?? to check, as well as assign something

var obj  = myObjVar ?? new MyObject();
like image 29
Habib Avatar answered Sep 20 '22 11:09

Habib