What is the difference between ==
and Equals()
with example? I know that ==
is used to compare operator and Equals()
method is used to compare content of string.So i tried
// first example
string s1 = "a";
string s2 = "a";
Console.Write(a.Equals(s2)); // returns true, but if I assign "b" to s2,
// then result will be false
// second example
string s1 ="a";
string s2 ="a";
Console.Write(s1 == s2); // returns true
How this is so? Both are different object references. Suppose we consider that these are reference. But I tried to use like this
string s1 = new string("ab");
string s2 = new string("ab");
I am getting compile time error that can not convert string to char
Quote from the documentation of Equals:
And the == operator:
Now back to your question: why does
s1 == s2
returns true? Strings are special beasts in .NET. They represent immutable reference types. They are interned in .NET. This means that if you have 2 string constants with the same value, they will refer to the same object instance at runtime.Quote from the documentation:
There are several things going on. Firstly, in this example:
You claim that:
That's not true due to string interning.
s1
ands2
are references to the same object. The C# specification guarantees that - from section 2.4.4.5 of the C# 4 specification:So in this particular case, you would still get "true" even if you printed
object.ReferenceEquals(s1, s2)
, or if you made it use a true reference identity comparison with==
:However, even if these were references to separate objects,
==
is overloaded forstring
. Overloading is a compile-time decision - the implementation to use depends on the compile-time types of the operands. So for example:Compare that with
object.Equals(object)
which is a virtual method. As it happens,String
overloads this method as well, but importantly it overrides it. So if we change our code to:... then both method calls in the compiled code will simply be to
object.Equals(object)
, but they'll still both print True because of polymorphism: the implementation inString
will be used.Here's what a call to the overloaded method would look like:
You're thinking seem Java-esque. In java, the
==
operator cannot be customized, so for reference types, it always means reference equality, while it means value equality for primitive types. On the other hand,Equals
is for checking value equality in reference types.Things are different in C#, though. Both
Equals
and==
can have custom implementations. The difference is thatEquals
is a virtual (instance) method, whileoperator==
is a static method. Aside from that, they can behave in exactly the same way.By default, both
Equals
and==
check reference equality for reference types, and value equality for value types. However, forstring
, both are customized to check value equality.