Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ReferenceEquals(null, obj) the same thing as null == obj?

Tags:

c#

Is it the same thing?

if (ReferenceEquals(null, obj)) return false;

and

if (null == obj) return false;
like image 464
Prankster Avatar asked Jun 09 '09 14:06

Prankster


2 Answers

You'd usually see this in the implementation of an == operator.

For instance:

public static bool operator ==(Foo f1, Foo f2)
{
    if (ReferenceEquals(f1, f2))
    {
        return true;
    }
    if (ReferenceEquals(f1, null) || ReferenceEquals(f2, null))
    {
        return false;
    }
    // Now do comparisons
}

You don't want to use:

if (f1 == f2)

because that will recurse into the same code! An alternative is:

if ((object)f1 == (object)f2)

(And the same for the null check.)

like image 73
Jon Skeet Avatar answered Sep 21 '22 22:09

Jon Skeet


It is the same thing if obj is typed as object.

If the variable's type defines a static equality operator or null operator, then it will be different; and if obj is defined as Nullable<T> then the compiler will step in and check HasValue instead.

like image 19
Marc Gravell Avatar answered Sep 23 '22 22:09

Marc Gravell