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
}
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.
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.
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.
You can use Object.ReferenceEquals
if (Object.ReferenceEquals(null, myObjVar))
{
.......
}
This would return true, if the myObjVar is null.
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();
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