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?
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.
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 .
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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With