Checking if an object is null in C#

Solution 1:

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;.

Solution 2:

in C# > 7 use if (obj is null)

For not null use
in C# 7-8:  if (obj is object)
and from C# 9: if (obj is not null)

These will ignore any == or != defined by the object (unless of course you want to use them for null checks)

Solution 3:

C# 6 has monadic null checking :)

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;

Solution 4:

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;
}

Solution 5:

[Edited to reflect hint by @kelton52]

Simplest way is to do object.ReferenceEquals(null, data)

Since (null==data) is NOT guaranteed to 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:

Comparing '' with 'Nully'

True

False