Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if an object is null in C#

People also ask

How do you check if something is a null pointer?

So that if p is a null pointer then it must compare equal to any null pointer including NULL , in which case p != NULL would evaluate to false. Conversely, if p points to an object or function then it must compare unequal to any null pointer in which case p != NULL would evaluate to true.

Is nullptr the same as null?

nullptr is a new keyword introduced in C++11. nullptr is meant as a replacement to NULL . nullptr provides a typesafe pointer value representing an empty (null) pointer. The general rule of thumb that I recommend is that you should start using nullptr whenever you would have used NULL in the past.

Are 0 and null the same in C?

NULL is use as an abstraction because at the time it was not clear what the value of NULL would be from system to system. So the standard value is zero, Which is the same for '0'. Using NULL or '0' you are sure your code would work on any system regardless of what their values are.


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 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)


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;

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

[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


As of C# 9 you can do

if (obj is null) { ... }

For not null use

if (obj is not null) { ... }

If you need to override this behaviour use == and != accordingly.