Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# shorthand for Equals() when both args can be null

Tags:

c#

null

equals

A simple question:

I want to compare two objects using the virtual Equals() method (not ==). Both can be null.

Should I repeat this litany:

if ((left == null && right == null) || (left != null && left.Equals(right)) {

}

or is there a more elegant idiom for such situation?

like image 792
Kos Avatar asked Apr 25 '12 19:04

Kos


1 Answers

Yup:

if (object.Equals(left, right))

or even without making it obvious that it's calling the static method:

if (Equals(left, right))

(Personally I prefer the extra clarity though.)

The static object.Equals method doesn't have terribly good documentation, but it does exactly what you want :)

like image 154
Jon Skeet Avatar answered Sep 19 '22 08:09

Jon Skeet