Checking if an object is null in C#
Asked Answered
G

22

319

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

Garofalo answered 20/6, 2011 at 21:40 Comment(10)
You should also use throw e; versus throw new Exception(e.ToString());Gyrostatics
Is the data object initialized before checking for null? Or is it coming from a database?Selfforgetful
in C# you should always use != null in your null checks. .Equals will always throw an exception if the object is null.Vlaminck
@Nix: throw e; is not much better. throw;, on the other hand...Hebetic
@Nix: What is the reason for doing throw e instead of what I have? (Thanks!)Garofalo
@developer: e.ToString() will produce a string that includes not only the error message, but also those of all InnerExceptions 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 simply throw;.Hebetic
@Gyrostatics ...and that's exactly why you should do it like @Hebetic suggestsEngagement
@Garofalo Just go with throw;Callicrates
The try/catch does nothing at the moment. Everyone is saying just use "throw" but if you aren't doing anything with the exception but re-throwing it, why have a try/catch block at all? Usually you catch exceptions to gracefully handle them, clean up resources (better with "finally" clause) or do some sort of logging before re-throwing the exception. None of these are happening in this code, so there's no need for try/catch at all.Allies
As a small update C# 7 supports is null, so for your first check you could write if (data is null) return false; to reduce nesting and make use of the (imo) cleaner syntax.Motmot
H
295

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

Hebetic answered 20/6, 2011 at 21:41 Comment(8)
I've seen also Object.ReferenceEquals(obj, null) for this purpose. Is it to avoid equality overrides?Pikeperch
@LucaPiccioni I've used it to prevent value-type-complains when using generics: geekality.net/2009/11/13/generics-and-checking-for-nullSarpedon
I prefer null != data. Putting the constant first turns the bonehead typo null = data into a compiler error, rather than an unintentional assignment. (Also works for ==.)Plastid
@jpmc26: In C# if (data = null) is already a compile time error, so even if it took decades to get there we don't really need to watch out for that anymore. Even C++ compilers will easily produce a warning about possible unintended assignment for that code.Hebetic
Luca, you can also avoid equality overrides by casting to 'object' in the test. On a similar vein, this answer should claim this instead: "if((object)data != null)" since it avoids errors when equality has been overriden.Spence
Just to extend your answer: whenever you see a NullReferenceException, you'll generally see that the null object is followed by a .. Using that as a rule of thumb, it becomes clear that the exception for datalist.Add(data) can only be about datalist. Comparatively; for datalist.Add(data.Value), the problem could be either in datalist or data. (Footnote: I had not seen that this was a 7 year necropost. I'm sorry)Molini
That's a solution to the asker's real problem, but not to the question indicated by the title, which I came here looking for (indeed, I was looking for the best way to check for null within an == operator overload). For this, see kofifus's answer.Whipping
"And if you do, rethrow them using just throw;." This is what one should be doing if the try/catch is there for debugging. If it isn't there for debugging, it shouldn't be there at all.Whipping
K
192

Use if (obj is null)

For not null use either:
   if (obj is object) or
   if (obj is not null) (C# > 9)

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

For more, in the C# Language Reference, see is operator.

Kreiner answered 4/7, 2018 at 1:3 Comment(12)
I wonder is there an "isn't null"? (python would say obj is not null)Maladminister
Why is that better than if( obj != null ) which is more readableLeung
Wish they'd implement if (obj aint null) :(Entrails
For isn't null there is if (obj is object)Hokanson
@OrnKristjansson because != and == can be overridden.Kaceykachina
I miss the IsNot operator from VB.NET (and the boolean operators And and Or - more readable than && and ||)Teplica
@Maladminister How about if ((obj is null).Equals(false)) ?Pail
FYI: there's an obj is not null now though, since .net 5 introducing C# 9 :) but the idea of having an obj aint null is hilarious, go open some feature request or whatever!Alber
A note here for anyone reading these comments, a lot of vb devs don't seem to grasp that And and Or are not equivalent to && and ||; the latter short-circuit, the former do not. The semantic equivalents are AndAlso/OrElseAplanospore
you can also do !(obj is null) for isn'tHumid
Just seen the edit with is not null logical pattern matching functionality, it's great to see an older answer updated with C# 9 featuresPrepossessing
is! That's it! It's the way to do it in D (a special case of reference comparison), but I thought in C# the RHS had to be a class.Whipping
M
86

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;
Macronucleus answered 7/2, 2014 at 7:50 Comment(1)
I came here in search of a better syntax to express result = myObject == null ? null : myObject.SomeProperty and your example tipped me off to write result = myObject?.SomeProperty. Man!! That's sneaky. I still love coding...Jacobin
I
28

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;
    }
    return success;
}
Incondensable answered 20/6, 2011 at 21:41 Comment(7)
Also, just to add, if data is null, it will not crash, you can add null to a List<Object>.Peon
But trying to do .Equals on a null would throw an exception. Should do != nullIncondensable
@glosrob: Ah!! What an oversight! I was thinking that the NullReferenceException was from the object.. not the list! I'm new to c# and I figured there was a special way of checking for null in c#!Garofalo
That too, but I saw Ed S. had covered it.Peon
@DaveShaw: Thanks for the heads up. I want to avoid a null object being added for later processing though, so I'll still do a check. :)Garofalo
@glosrob: ah ic! I will change all .Equals to != null. Thanks for the heads up!Garofalo
+1 but I selected Jon's answer because he went into more detail about NullReferenceException. Thanks though! :DGarofalo
A
26

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.

Axiology answered 20/5, 2020 at 16:50 Comment(1)
Just want to point something out...in case of not null it can be if(obj is object)Shilohshim
M
22

[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

Millymilman answered 11/4, 2012 at 11:17 Comment(1)
Actually I just tried this, and the remark 'The implied advantage is that it ignores any overrides that may be present in data's class, like "operator !=".' Doesn't seem to hold true.Leicestershire
P
10

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.

Pretzel answered 20/6, 2011 at 21:42 Comment(0)
E
8

With c#9 (2020) you can now check a parameter is null with this code:

if (name is null) { }

if (name is not null) { }

You can have more information here

Euphrates answered 15/9, 2020 at 8:19 Comment(0)
F
7

The problem in this case is not that data is null. It is that dataList itself is null.

In the place where you declare dataList you should create a new List object and assign it to the variable.

List<object> dataList = new List<object>();
Freudberg answered 20/6, 2011 at 21:42 Comment(0)
E
6

As of C# 8 you can use the 'empty' property pattern (with pattern matching) to ensure an object is not null:

if (obj is { })
{
    // 'obj' is not null here
}

This approach means "if the object references an instance of something" (i.e. it's not null).

You can think of this as the opposite of: if (obj is null).... which will return true when the object does not reference an instance of something.

For more info on patterns in C# 8.0 read here.

Eddo answered 13/1, 2020 at 11:7 Comment(5)
This looks like each time this runs it allocates a new object, which is adding unneeded GC pressure/is an anti-pattern.Damondamour
Is that an assumption or a fact? The compiled output in a test app shows that it gets compiled to a simple != null check.Eddo
you're correct, that was an assumption, because that's object initializer syntax. But even on debug builds it compiles to ldloc.0; ldnull; cgt.un which means you're absolutely correct, no allocation happens. I'm very surprised and apologies for causing confusion.Damondamour
If it is compiled to the simpler != null, why would this be an improvement, given that != null is more legible?Aplanospore
@Aplanospore because the != operator can be overloaded in a class (thus invoking the custom implementation) whereas the above uses pattern matching which will not invoke any overloaded operators. I'm not in a position to check right now but I believe the compiled output of the above code will always cast the object to object (ensuring to not call any overloaded operators).Eddo
E
5

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 //
   }
Essa answered 17/6, 2017 at 9:28 Comment(5)
Why return T == null ? true : false; and not just return T == null;?Sheer
I'm not sure I agree. It looks strange to be calling a method on an object to check if it is null. Without knowing it was an extension method you would think it would throw a null reference exception.Longwood
Can totally confirm that Jamie is correct - this will not work. I know because I had a hare-brained moment and wrote a similar extension method :P The code always threw a null reference exception, it absolutely will not go into the extension method.Harms
Actualy I want to say youcan do thatwith extention method... may be the code have some problem and can improve!Essa
You can call an extension method on a null object; you just need to compare T (in this case) against null to be careful. Jamie is right, though, it looks odd.Hauteur
I
2

Jeffrey L Whitledge is right. Your `dataList´-Object itself is null.

There is also another problem with your code: You are using the ref-keyword, which means the argument data cannot be null! The MSDN says:

An argument passed to a ref parameter must first be initialized. This differs from out, whose arguments do not have to be explicitly initialized before they are passed

It's also not a good idea to use generics with the type `Object´. Generics should avoid boxing/unboxing and also ensure type safety. If you want a common type make your method generic. Finally your code should look like this:

public class Foo<T> where T : MyTypeOrInterface {

      public List<T> dataList = new List<T>();

      public bool AddData(ref T data) {
        bool success = false;
        try {
          dataList.Add(data);                   
          success = doOtherStuff(data);
        } catch (Exception e) {
          throw new Exception(e.ToString());
        }
        return success;
      }

      private bool doOtherStuff(T data) {
        //...
      }
    }
Impute answered 21/6, 2011 at 8:51 Comment(0)
R
2

As others have already pointed out, it's not data but rather likely dataList that is null. In addition to that...

catch-throw is an antipattern that almost always makes me want to throw up every time that I see it. Imagine that something goes wrong deep in something that doOtherStuff() calls. All you get back is an Exception object, thrown at the throw in AddData(). No stack trace, no call information, no state, nothing at all to indicate the real source of the problem, unless you go in and switch your debugger to break on exception thrown rather than exception unhandled. If you are catching an exception and just re-throwing it in any way, particularly if the code in the try block is in any way nontrivial, do yourself (and your colleagues, present and future) a favor and throw out the entire try-catch block. Granted, throw; is better than the alternatives, but you are still giving yourself (or whoever else is trying to fix a bug in the code) completely unnecessary headaches. This is not to say that try-catch-throw is necessarily evil per se, as long as you do something relevant with the exception object that was thrown inside the catch block.

Then there's the potential problems of catching Exception in the first place, but that's another matter, particularly since in this particular case you throw an exception.

Another thing that strikes me as more than a little dangerous is that data could potentially change value during the execution of the function, since you are passing by reference. So the null check might pass but before the code gets to doing anything with the value, it's changed - perhaps to null. I'm not positive if this is a concern or not (it might not be), but it seems worth watching out for.

Richards answered 21/6, 2011 at 12:12 Comment(0)
L
2
  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 and 01/25/2021. Thanks for the comment.

public static bool IsNull(object T)
{
    return (bool)T ? true : false;
}

Demostration Demostration on Visual Studio console application

And for the records, you have my code on Github, go check it out: https://github.com/j0rt3g4/ValidateNull PS: This one is especially for you Chayim Friedman, don't use beta software assuming that is all true. Wait for final versions or use your own environment to test, before assuming true beta software without any sort of documentation or demonstration from your end.

Lutes answered 31/1, 2017 at 18:0 Comment(11)
cond ? true : false; is completely equivalent to just cond. This adds nothing.Subacid
I'm sorry but if you check the function it must return a bool value. I'm doing the formalism. So re-check itLutes
he means return T == null; also returns a boolean!Oogonium
I know what hes saying. tyLutes
Instead of return T == null ? true : false; just use return T == null;.Sheer
Does return T ? true : false; really return true if T is null?Sheer
Yes sir, try it.Lutes
@JoseOrtega No it's not, try itAlbrecht
@chayimfriedman Excellent, I've updated it now, thank you for the comment.Lutes
@JoseOrtega That does not work eitherAlbrecht
Probably is the web application that it doesn't work correctly. I'll add the screenshot :)Lutes
S
2

There is a one-liner in .NET 6

ExampleMethod(null);

void ExampleMethod(object param)
{
    ArgumentNullException.ThrowIfNull(param);
    // Do something
}
Sophia answered 25/2, 2022 at 8:10 Comment(0)
G
1

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
  }
}
Grisham answered 29/4, 2018 at 18:34 Comment(0)
K
0

I just followed a method that we would usually follow in java script. To convert object to string and then check whether they are null.

var obj = new Object();
var objStr = obj.ToString();
if (!string.IsNullOrEmpty(objStr)){
  // code as per your needs
}
Kilan answered 22/8, 2019 at 6:4 Comment(0)
J
0

I did more simple (positive way) and it seems to work well.

Since any kind of "object" is at least an object


    if (MyObj is Object)
    {
            //Do something .... for example:  
            if (MyObj is Button)
                MyObj.Enabled = true;
    }

Japonica answered 11/3, 2020 at 15:54 Comment(0)
N
0

You can try like below

public List<Object> dataList;
public  bool AddData(ref Object data)
bool success = false;
try
{
    if (data != null)
    {
       dataList.Add(data);
       success = doOtherStuff(data);
    }
}
catch (Exception e)
{
    throw new Exception(e.ToString());
}
return success;

}

Neuropathy answered 19/11, 2020 at 2:3 Comment(0)
S
0

Here are some extensions I use:

/// <summary>
/// Extensions to the object class
/// </summary>
public static class ObjectExtensions
{
    /// <summary>
    /// True if the object is null, else false
    /// </summary>
    public static bool IsNull(this object input) => input is null;

    /// <summary>
    /// False if the object is null, else true
    /// </summary>
    public static bool NotNull(this object input) => !IsNull(input);
}
Siliqua answered 6/1, 2021 at 8:49 Comment(0)
V
-1
public bool IsVisible(object ClaimCount)
    {
        bool flag = true;
        #region || HIDE COLUMNS ON CONDITION BASIS
        if (!String.IsNullOrEmpty(Convert.ToString(ClaimCount)))
        {
            Int32 ClaimCnt = Convert.ToInt32(ClaimCount);
            if (ClaimCnt == 1)
            {
                flag = false;
            }
        }
        #endregion
        return flag;
    }
Vagabondage answered 13/3, 2021 at 10:20 Comment(1)
This doesn't seem to answer the question, which is regarding checking if a reference is null.Padriac
A
-1

A few additional options that have not been mentioned.

The NULL propagation method for NULL check

if (value?.Name == null) {
    Console.WriteLine(“value is null.”);
}

Using the Null Coalescing operator

Var test = value ?? “value is null”;

C# v.7 will support pattern matching

if (value is null) {
    Console.WriteLine(“value is null.”);
}

if (!(value is null)) {
    Console.WriteLine(“value is null.”);
}

if (value is object) {
    Console.WriteLine(“value is not null.”);
}

C# v.8 improved the “is object” Null check, We can use these curly braces to check whether the value is not Null.

if(value is {}) {
    Console.WriteLine(“value is not null.”);
}

Null Coalescing assignment

Value ??= “assign string or int or any object”;

And finally with c# v.9

if (value is not null)
{
    Console.WriteLine(“value is null.”);
}
Artieartifact answered 23/1 at 2:27 Comment(4)
Welcome to SO. C# has a case sensitive syntax. Your lines won't compile. You should review them.Freesia
@Freesia good call, syntax updated, please review, and update usefulnessArtieartifact
You must also update the Var keyword for it to compile properly and you should update Value keyword for readability. By the way, I don't know what you mean by "review", but I'm not the one who voted downvote :( If I were to do that, I wouldn't make these suggestions :)Freesia
@Freesia I see what you are getting at, I was however trying to keep the code representative in a sudo code fashion to allow for easy readability, expecting users understand how variables are initialized, I will take your comment on board and attempt to provide 'useable' example in the future, ty.Artieartifact

© 2022 - 2024 — McMap. All rights reserved.