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)?
It’s not
datathat isnull, butdataList.You need to create one with
Even better: since it’s a field, make it
private. And if there’s nothing preventing you, make it alsoreadonly. Just good practice.Aside
The correct way to check for nullity is
if(data != null). This kind of check is ubiquitous for reference types; evenNullable<T>overrides the equality operator to be a more convenient way of expressingnullable.HasValuewhen checking for nullity.If you do
if(!data.Equals(null))then you will get aNullReferenceExceptionifdata == null. Which is kind of comical since avoiding this exception was the goal in the first place.You are also doing this:
This is definitely not good. I can imagine that you put it there just so you can break into the debugger while still inside the method, in which case ignore this paragraph. Otherwise, don’t catch exceptions for nothing. And if you do, rethrow them using just
throw;.