There are different things to keep in mind here.
First, all identical constant strings will be interned so that both references are equal to start with. Therefore, even if you did a ReferenceEquals()
here, you'd get "true" as result. So only for a string built (for instance with a StringBuilder
, or read from a file etc.) you'd get another reference and therefore false when doing a reference equality comparison.
If both objects are known to be strings at compile time, the compiler will emit code to compare their value (==
overloaded operator on System.String
), not their references. Note that as soon as you compare it against an object
type reference, this isn't the case anymore.
No runtime check is done to compare a string by value, and the compiler does not emit a .Equals()
call for the ==
operator.