Reputation: 7035
Edit:
Why this question is not duplicate?
I'm not asking difference between .Equals()
and ==
. I'm asking how does actually ==
work. I mean, when I created strings using different method, I should have seen different result. But I see same result.
I was looking into ==
operator in c#. To my surprise it gave same result for following codes (contrary to JAVA). But according to this, ==
is for reference check and I should see different result for my code then why do I see same result for both of them? Shouldn't I see different results for my piece of codes? Is it because new String()
in c# doesn't generate new reference?
String s = "abc";
String s1 = "abc";
Console.WriteLine("Expected output: True, Actual output: " + (s1==s).ToString());
Output
Expected output: True, Actual output: True
Another code check
String s2 = new String("abc".ToCharArray());
String s3 = new String("abc".ToCharArray());
Console.WriteLine("Expected output: False, Actual output: " + (s2 == s3).ToString());
Output
Expected output: False, Actual output: True
Note: I understand difference reference & value check. I've tried result with ReferenceEquals
and it shows expected result to me.
Upvotes: 1
Views: 184
Reputation: 48558
Normally for reference types ==
operator do check for reference equality.
String is also a reference type but in String class ==
operator is overloaded to check for content equality and not reference equality.
It says and I quote
Determines whether two specified strings have the same value.
Read here https://msdn.microsoft.com/en-us/library/system.string.op_equality(v=vs.110).aspx
FYI, in string !=
operator is also oveloaded to check for string content inequality.
Upvotes: 7