R.C
R.C

Reputation: 10565

Why does == for String variables returns true?

With reference to this question why does the below code always returns true? [ c# Language ]

String a= "hello";
String b= "hello";
if(a==b)
Console.WriteLine("Is it really reference type?");

Just want an explanation as to why here they behave as Value types and not reference types. Is there any MSDN documentation on this OR should I just memorize this exception OR is this completely logical but i'm not getting it?

Detailed explanation appreciated.

Upvotes: 0

Views: 132

Answers (3)

Matthias Meid
Matthias Meid

Reputation: 12523

The == operator for strings is overloaded to check value equality instead of reference equality, even though String is a reference type. Microsoft recommends to do this for reference types that have value semantics:

However, if you are implementing a reference type that is intended to have value semantics, such as a complex number type, you must override the equality operator.

See Object.Equals Method (Object) for more details.

Upvotes: 2

Kenneth
Kenneth

Reputation: 28737

In .NET strings are treated a bit differently. Although they are reference types, they seem to act as value types.

The basic reason for this is that strings are immutable and unique. What this means is that when you define string a, the value "hello" is saved on the heap.

When you define string b and assign it the value "hello" it will know that there's already a string with that value on the heap on create a pointer to that same string. It can safely do this because strings are immutable and therefore the CLR knows that that string will never be modified. Any operation that modifies the string, will just result in a new string being allocated on the heap.

Upvotes: 2

Knaģis
Knaģis

Reputation: 21485

Any class can override the == operator to provide a custom comparison. Documentation.

That is what String class does - it just provides a different meaning for the comparison - it checks the string values and not the object references.

If you really want to check if the instances point to the same reference, use object.ReferenceEquals(a, b)

As far as strings go, they actually are identical references in this case - the compiler will detect that the string values are exactly the same and just store them once in the memory. Here's something to read regarding String.Intern

Upvotes: 12

Related Questions