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.Equal
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
void myFunction(object1)
{
if(object1!=null)
{
object1.value1 //If we miss the null check then here we get the Null Reference exception
}
}
Your dataList is null as it has not been instantiated, judging by the code you have posted.
Try:
public List<Object> dataList = new List<Object>();
public bool AddData(ref Object data)
bool success = false;
try
{
if (!data.Equals(null)) // I've also used if(data != null) which hasn't worked either
{
dataList.Add(data); //NullReferenceException occurs here
success = doOtherStuff(data);
}
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
return success;
}
No, you should be using !=
. If data
is actually null then your program will just crash with a NullReferenceException
as a result of attempting to call the Equals
method on null
. Also realize that, if you specifically want to check for reference equality, you should use the Object.ReferenceEquals
method as you never know how Equals
has been implemented.
Your program is crashing because dataList
is null as you never initialize it.
public static bool isnull(object T)
{
return T == null ? true : false;
}
use:
isnull(object.check.it)
Conditional use:
isnull(object.check.it) ? DoWhenItsTrue : DoWhenItsFalse;
Update (another way) updated 08/31/2017. Thanks for the comment.
public static bool isnull(object T)
{
return T ? true : false;
}
It's not data
that is null
, but dataList
.
You need to create one with
public List<Object> dataList = new List<Object>();
Even better: since it's a field, make it private
. And if there's nothing preventing you, make it also readonly
. Just good practice.
Aside
The correct way to check for nullity is if(data != null)
. This kind of check is ubiquitous for reference types; even Nullable<T>
overrides the equality operator to be a more convenient way of expressing nullable.HasValue
when checking for nullity.
If you do if(!data.Equals(null))
then you will get a NullReferenceException
if data == null
. Which is kind of comical since avoiding this exception was the goal in the first place.
You are also doing this:
catch (Exception e)
{
throw new Exception(e.ToString());
}
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;
.
In addition to @Jose Ortega answer, its better for use extension method
public static bool IsNull(this object T)
{
return T == null;
}
And use IsNull
method for all of object like:
object foo = new object(); //or any object from any class
if (foo.IsNull())
{
// blah blah //
}