I would like to prevent further processing on an object if it is null.
In the following code I check if the object is null by either:
if (!data.Equals(null))
and
if (data != null)
However, I receive a NullReferenceException
at dataList.Add(data)
. If the object was null, it should never have even entered the if
-statement!
Thus, I'm asking if this is proper way of checking if an object is null:
public List<Object> dataList;
public bool AddData(ref Object data)
bool success = false;
try
{
// I've also used "if (data != null)" which hasn't worked either
if (!data.Equals(null))
{
//NullReferenceException occurs here ...
dataList.Add(data);
success = doOtherStuff(data);
}
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
return success;
}
If this is the proper way of checking if the object is null, what am I doing wrong (how can I prevent further processing on the object to avoid the NullReferenceException)?
[Edited to reflect hint by @kelton52]
Simplest way is to do
object.ReferenceEquals(null, data)
Since
(null==data)
is NOT guaranteed to work:Produces:
C# 6 has monadic null checking :)
before:
after:
Your dataList is null as it has not been instantiated, judging by the code you have posted.
Try:
}
The problem in this case is not that
data
is null. It is thatdataList
itself is null.In the place where you declare
dataList
you should create a newList
object and assign it to the variable.Whenever you are creating objects of class you have to check the whether the object is null or not using the below code.
Example: object1 is object of class
in C# 7 the best is
if (obj is null)
...This will ignore any == or != defined by the object (unless of course you want to use them ...)
For not equal you can
if (!(obj is null))
(ugly)