In C#, what do ==, Equals and object.ReferenceEquals each compare for two strings, and why does that change when they are typed as object?
answer
- operators bind at compile time
- string declares its own ==
- Equals is virtual
- CS0252: possible unintended reference comparison
basics
~20 sIn C#, == is picked at compile time from the operands' static types: string's overload compares characters, but on two object-typed variables it tests references. Equals is virtual and still compares content; ReferenceEquals always tests identity.
solid answer
~40 s`==` is an operator, and C# chooses operators at compile time from the **static** types of the operands. `string` declares `operator ==`, so `a == b` on two `string` variables compares length and characters ordinally. Type both as `object` and the compiler can only pick `object`'s built-in reference comparison, so two separate strings with the same text compare `False`; mix `object` and `string` and you get warning CS0252 or CS0253. `Equals` is a virtual method, so `oa.Equals(ob)` still runs `string.Equals` and compares content. `object.ReferenceEquals` ignores every override and overload and answers only "same object?". For a class with no overrides, `==` and `Equals` both test identity.
code
csharp · 11 linesstring a = "SKU-42";
string b = string.Concat("SKU-", 42.ToString()); // built at run time
object oa = a;
object ob = b;
Console.WriteLine(a == b); // string's operator ==
Console.WriteLine(a.Equals(b)); // string.Equals override
Console.WriteLine(oa == ob); // both typed object: reference test
Console.WriteLine(oa.Equals(ob)); // virtual call: still string.Equals
Console.WriteLine(object.ReferenceEquals(a, b)); // identity only
Console.WriteLine(oa == b); // warning CS0252go deeper
Recall that string == compares text, that a class with no overrides compares references, and that ReferenceEquals always tests identity. Be ready to say what happens when strings are typed as object.
Explain that operators bind at compile time from static types while Equals dispatches at run time, and use that to predict the result of any mix of string and object variables, including the CS0252 warning.
Show where the trap hides in real code: values stored as object in dictionaries, interface-typed properties, generic helpers. Explain why you would reach for object.Equals(a, b) there and treat CS0252 as an error.
Frame it as a team rule: equality through object-typed APIs goes through Equals, never ==, and reference-comparison warnings are build errors, because the bug compiles cleanly otherwise.
## Three ways to ask "are these equal?" C# gives you three tools, and they answer different questions: - **`==`** is an **operator**. Operators are static members, so the compiler picks which `==` to call while compiling, using the declared (static) types of the two operands. - **`Equals(object?)`** is a **virtual method** declared on `System.Object`. The call is dispatched at run time to the override of the object's actual (run-time) type. - **`object.ReferenceEquals(a, b)`** is a static method that returns `true` only when both arguments refer to the same object (or both are `null`). Overrides and operator overloads never affect it. **Reference equality** (also called identity) means "the two variables point at one object". **Value equality** means "the two objects hold the same data". A plain class gets reference equality from all three tools; a type opts into value equality by overriding `Equals` and, if it wants the operator too, declaring `operator ==`. ## Strings: an overloaded operator and an overridden method `string` is a reference type that does both. It overrides `Equals` and declares `operator ==` and `operator !=`, and both compare the two strings ordinally: same length, same UTF-16 characters in every position. That is why `a == b` on two `string` variables is `True` even when `b` was built at run time and is a different object from `a`. | Expression (a and b hold "SKU-42", different objects) | Static types | Which member runs | Result | |---|---|---|---| | `a == b` | string, string | `string.operator ==` | True | | `a.Equals(b)` | string, string | `string.Equals` | True | | `oa == ob` | object, object | built-in reference comparison | False | | `oa.Equals(ob)` | object, object | `string.Equals` (virtual dispatch) | True | | `object.ReferenceEquals(a, b)` | any | identity only | False | ## Why the static type decides Because `==` is resolved by overload resolution at compile time, the compiler only sees what the variable is **declared** as. When both operands are `object`, the only candidate is the predefined reference-type equality, so the run-time fact that both objects are strings never matters. When one operand is `object` and the other `string`, the compiler still picks reference equality but suspects a mistake and reports: 1. **CS0252**: "Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'" when the left side is the `object` one. 2. **CS0253**: the same message for the right hand side. The same trap appears wherever a string travels as `object`: a `Dictionary<string, object>` value, an `object` parameter, or a property typed as an interface. `Equals` does not have the problem, because virtual dispatch looks at the run-time type. ## Classes and structs that override nothing - A **class** without overrides inherits `Object.Equals`, which tests identity, and the predefined `==`, which tests identity too. Two `Sku` objects with identical properties are not equal by either. - A **struct** without overrides inherits `ValueType.Equals`, which compares the field values, but it gets **no** `==` at all: `p == q` fails with CS0019, "Operator '==' cannot be applied to operands of type 'Pos' and 'Pos'", until the struct declares the operator. The cost of the inherited `ValueType.Equals` is a matter for the lesson on value-type trade-offs. - **Records** generate value-based `Equals` and `==`; that generated code belongs to the records material. ## What to write in practice - Compare two `string` variables with `==`; it is null-safe because the operator is static. - When either side may be typed `object`, call the static `object.Equals(a, b)`: it returns `true` for the same reference, `false` if exactly one is `null`, and otherwise calls the virtual `Equals`. - Use `string.Equals(a, b)` (static) rather than `a.Equals(b)` when `a` might be `null`; the instance call throws `NullReferenceException` on a `null` receiver. - Use `object.ReferenceEquals` only when you really mean identity, for example inside an `Equals` override as a fast path, or when a type overloads `==` and you need to bypass it. - Treat CS0252 and CS0253 as bugs, not noise: add the cast the message suggests or switch to `Equals`. Culture-aware or case-insensitive comparison (`StringComparison`, `StringComparer`) is a separate subject covered with string comparison; `==` on strings is always the case-sensitive ordinal check.
- Why is `a == null` safe on a `string` variable that holds null, while `a.Equals("x")` throws?`string`'s `operator ==` is a static method, so it runs without a receiver and handles a `null` operand by returning `true` only when both are `null`. `a.Equals("x")` is an instance call; with `a` null there is no object to dispatch on, so the runtime throws `NullReferenceException`. The static `string.Equals(a, b)` or `object.Equals(a, b)` avoids that.
- What does `==` do for a plain struct and for a plain class that override nothing?For a class, `==` is the predefined reference comparison: `True` only for the same object, whatever the properties hold. For a struct, there is no predefined `==` at all, so `p == q` is error CS0019 until the struct declares `operator ==` and `operator !=`. Calling `Equals` on the struct still works, because `ValueType.Equals` compares its fields.
Two printed copies of the same receipt: reading them side by side (Equals) says they match, while asking whether they are the same sheet of paper (ReferenceEquals) says no. == reads them only when it knows they are receipts; told only that they are "paper", it checks whether you are holding one sheet.
- == on two strings always compares characters, whatever the variables are declared as
- Equals and == always give the same answer for any C# type
- ReferenceEquals compares contents when a type overrides Equals
- Casting a string to object keeps string's == because the object is still a string
- CS0252 is a harmless style warning that can be suppressed