Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between x is null and ReferenceEquals(x, null)?

Tags:

c#

When I write this:

ReferenceEquals(x, null)

Visual studio suggests that the

null check can be simplified.

and simplifies it to

x is null

Are those really the same?

like image 464
Michael Haddad Avatar asked Feb 23 '18 10:02

Michael Haddad


People also ask

Should I use is or == C#?

The is keyword has the big advantage that it ignores any operator overloads that are defined on the class of the instance you want to check. When you use the == operator, it could be possible that this operator is overloaded and you get an unexpected result. Let's look at a simple example.

Is null or equal null C#?

ReferenceEquals returns true when the object instances are the same instance. In this case, it returns true when obj is null. Equals is similar to ReferenceEquals when one argument is null .

How do you check if the object is null or not in C#?

In C#, IsNullOrEmpty() is a string method. It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String.


1 Answers

I noticed a lot of answers specifying that x == null, x is null, and ReferenceEquals(x, null) are all equivalent - and for most cases this is true. However, there is a case where you CANNOT use x == null as I have documented below:

Note that the code below assumes you have implemented the Equals method for your class:

Do NOT do this - the operator == method will be called recursively until a stack overflow occurs:

public static bool operator ==(MyClass x1, MyClass x2)
{
   if (x1 == null)
      return x2 == null;

   return x1.Equals(x2)
}

Do this instead:

public static bool operator ==(MyClass x1, MyClass x2)
{
   if (x1 is null)
      return x2 is null;

   return x1.Equals(x2)
}

Or

public static bool operator ==(MyClass x1, MyClass x2)
{
   if (ReferenceEquals(x1, null))
      return ReferenceEquals(x2, null);

   return x1.Equals(x2)
}
like image 134
mdebeus Avatar answered Sep 29 '22 12:09

mdebeus