Problem
If an object is null, I’d like to prohibit it from being processed further.
I verify if the object is null using the following code:
if (!data.Equals(null))
and
if (data != null)
However, at dataList, I get a NullReferenceException. Add(data). The item should never have entered the if-statement if it was null!
As a result, I’m wondering if this is the right approach to check 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;
}
What am I doing wrong (how can I prohibit further processing on the object to avoid the NullReferenceException) if this is the right technique of testing if the object is null?
Asked by developer
Solution #1
It’s dataList, not data, that’s missing.
You’ll need to come up with one.
public List<Object> dataList = new List<Object>();
Even better, make it private because it’s a field. If there’s nothing stopping you, make it readonly as well. It’s simply good practice.
Aside
If(data!= null) is the correct approach to check for nullity. This type of check is common in reference types; in fact, NullableT> overrides the equality operator to express nullable in a more accessible way. When checking for nullity, use HasValue.
If data == null, you’ll get a NullReferenceException if you use if(!data.Equals(null)). Which is kind of ironic, given that the purpose was to prevent this exception in the first place.
You’re also doing it.
catch (Exception e)
{
throw new Exception(e.ToString());
}
This is clearly not a favorable situation. I’m guessing you put it there only to get into the debugger while still inside the method, in which case you can ignore the rest of this text. Otherwise, don’t make exceptions just to make an exception. If you do, use only toss; to rethrow them.
Answered by Jon
Solution #2
Use if in C# > 7 (obj is null)
In C# 7-8, use not null: if (obj is object) and if (obj is object) from C# 9 (obj is not null)
Any == or!= specified by the object will be ignored (unless of course you want to use them for null checks)
Answered by kofifus
Solution #3
Monadic null checking is available in C# 6:)
before:
if (points != null) {
var next = points.FirstOrDefault();
if (next != null && next.X != null) return next.X;
}
return -1;
after:
var bestValue = points?.FirstOrDefault()?.X ?? -1;
Answered by Jowen
Solution #4
According to the code you posted, your dataList is null because it has not been instantiated.
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;
}
Answered by glosrob
Solution #5
[Edited to include @kelton52’s suggestion]
The simplest method is to use an object. EqualsReferences (null, data)
Because (null==data) may or may not work:
class Nully
{
public static bool operator ==(Nully n, object o)
{
Console.WriteLine("Comparing '" + n + "' with '" + o + "'");
return true;
}
public static bool operator !=(Nully n, object o) { return !(n==o); }
}
void Main()
{
var data = new Nully();
Console.WriteLine(null == data);
Console.WriteLine(object.ReferenceEquals(null, data));
}
Produces:
Answered by gatopeich
Post is based on https://stackoverflow.com/questions/6417902/checking-if-an-object-is-null-in-c-sharp