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)?
throw e;
versusthrow new Exception(e.ToString());
– Gyrostaticsdata
object initialized before checking for null? Or is it coming from a database? – Selfforgetful!= null
in your null checks..Equals
will always throw an exception if the object is null. – Vlaminckthrow e;
is not much better.throw;
, on the other hand... – Hebeticthrow e
instead of what I have? (Thanks!) – Garofaloe.ToString()
will produce a string that includes not only the error message, but also those of allInnerExceptions
and the stack trace. So that's kind of a very fat-heavy exception message. If you (rightly!) want to preserve this information, and keep where it belongs, use simplythrow;
. – Hebeticthrow;
– Callicratesis null
, so for your first check you could writeif (data is null) return false;
to reduce nesting and make use of the (imo) cleaner syntax. – Motmot