Adam
Adam

Reputation: 1493

Why do I get a null reference error when using something.Equals(null) in C#

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?

Upvotes: 1

Views: 107

Answers (4)

valverij
valverij

Reputation: 4941

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

Upvotes: 6

AFrieze
AFrieze

Reputation: 844

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

Upvotes: 1

AlG
AlG

Reputation: 15157

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

Upvotes: 0

Konrad Kokosa
Konrad Kokosa

Reputation: 16888

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)

Upvotes: 2

Related Questions