1

I keep getting a null reference error when I am trying to check if something is null. I have a class called User and I initialize the variable indvUser like so

User indvUser = api.Users.SearchByExternalId(session.UserInfo.UserId.ToString())
                   .Users.FirstOrDefault();

Then I want to check if indvUser is null like this

if (indvUser.Equals(null))
{
    int a = 1;
}

But I get a null reference error when using Equals(null) which I don't understand. If it actually is null i.e. there is no value, shouldn't Equals(null) return true?

2
  • 3
    Why not use if (indvUser == null)?? Commented Dec 17, 2013 at 19:09
  • That is what I ended up doing, but I was curious why this wouldn't work. Commented Dec 17, 2013 at 21:33

4 Answers 4

6

Since indvUser is null, and indvUser.Equals is an instance method on your User object (i.e., it requires an non-null instance of your object), .NET will throw the error you attempt to use it.

For something like this, you could use this:

Object.ReferenceEquals(indvUser, null)

Or simply:

indvUser == null

Since neither of these approaches actually attempt to access methods or properties on the indvUser object itself, you should be safe from NullReferenceExceptions

Sign up to request clarification or add additional context in comments.

1 Comment

Object.equals already calls ReferenceEquals msdn.microsoft.com/en-us/library/bsc2ak47(v=vs.110).aspx
2

In line:

indvUser.Equals(null)

if indvUser is null, how Equals method could be called on it? It simply can be seen as:

null.Equals(null)

You should compare it as indvUser == null or object.ReferenceEquals(indvUser, null)

1 Comment

Good explanation as to WHY the NullReferenceException is occurring.
1

Object.Equals is a method which is not static. In order to call the Equals method, you must have an instance of the class.

Comments

0

If indUser == null you'd be doing null.Equals(null) which would throw an exception.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.