0

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.

Community
  • 1
  • 1
R.C
  • 10,417
  • 2
  • 35
  • 48

3 Answers3

12

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

Knaģis
  • 20,827
  • 7
  • 66
  • 80
  • Great! Finally i understood how is this working. It is basically the operator == defined this way only to Compare the Values and not references. Thanks for sharing the MSDN path. – R.C May 16 '13 at 10:59
2

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.

Kenneth
  • 28,294
  • 6
  • 61
  • 84
2

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.

Matthias Meid
  • 12,455
  • 7
  • 45
  • 79