0

I generally work in JavaScript but have been tasked with combing through some C# code that was written several years to replace it.

I came across one example I'm trying to wrap my head around. From my understanding ReferenceEquals() is used to compare two objects to determine if they are the same instance. But in the code I'm looking at the second parameter passed in is not an object, but null:

string type = ReferenceEquals(employee.wage_type, null)
                              ? "W2"
                              : employee.wage_type.Replace(".", string.Empty);

So, my question is, what is this doing here? Is it effectively saying, if employee.wage_type is equal to null then assign "W2". If not, take the found value of . and replace it with an empty string? Does that sound correct?

And if so, wouldn't it have been simpler just to check if the value was null directly, rather than using ReferenceEquals() which is meant to compare objects? Or am I misunderstanding what ReferenceEquals() can/is used for?

Banon
  • 53
  • 6
  • if `employee.wage_typε` is `null` then use a default value ("W2") else get the value (after some string manipulation) – Nikos M. Oct 30 '20 at 17:52
  • Try writing `string type = (employee.wage_type === default(string)) ? "W2" : employee.wage_type.Replace(".", string.Empty);` – Kunal Mukherjee Oct 30 '20 at 17:52
  • @Banon definitely. `someValue == null` unless you have reason to believe the type specifies a buggy equality operator that can't handle nulls. Or `someValue is null` using the new pattern matching syntax, which checks types – Panagiotis Kanavos Oct 30 '20 at 17:55

1 Answers1

7

From my understanding ReferenceEquals() is used to compare two object to determine if they are the same instance

Well, not quite. It's used to determine if two references are identical. It's absolutely fine for those references to be null.

And if so, wouldn't it have been simpler just to check if the value was null directly, rather than using ReferenceEquals() which is meant to compare objects?

It can make a difference if the type overloads the == operator itself. ReferenceEquals always, always compares the references directly - whereas the == operator can perform user-specified code (e.g. string has an overload of bool ==(string, string)).

In modern C# code, the more idiomatic approach is to use pattern matching:

string type = employee.wage_type is null
    ? "W2"
    : employee.wage_type.Replace(".", string.Empty);

... but in this case I'd actually use the null-safe dereferencing operator instead:

string type = employee.wage_type?.Replace(".", "") ?? "W2";

(I'd also rename wage_type to follow .NET naming conventions, mind you.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194