3

Consider the following code:

public static void Main()
{
    string str1 = "abc";
    string str2 = "abc";

    if (str1 == str2)
    {
        Console.WriteLine("True");
    }
    else
    {
        Console.WriteLine("False");
    }

    Console.ReadLine();
}

The output is "True". string is a reference type in .Net & I am comparing two different objects, but still the output is "True".

  1. Is is because it internally calls ToString() method on both objects & before comparing them?
  2. Or is it because a string is an immutable type? Two completely distinct string objects having the same value would point to same memory location on the heap?

How does string comparison happens?

How does memory allocation works on the heap? Will two different string objects with the same value point to same memory location, or to a different one?

Mathieu Guindon
  • 69,817
  • 8
  • 107
  • 235
Atul Sureka
  • 3,085
  • 7
  • 39
  • 64
  • At first I felt like downvoting for "not enough research", as you could quickly find that `string` is a special case of a reference type in .net, but seeing some of the answers and comments your question has generated I actually learned something, so +1! – Mathieu Guindon Aug 30 '13 at 02:35

5 Answers5

6
  • Strings are compared by value by default.
  • Objects are compared by reference by default.
  • Identical string literals in the same assembly are interned to be the same reference.
  • Identical strings that are not literals can legally be interned to the same reference, but in practice typically are not.

So now you should be able to understand why you get the given output in this program fragment:

string a1 = "a";
string a2 = "a";
string aa1 = a1 + a2;
string aa2 = a1 + a2;
object o1 = a1;
object o2 = a2;
object o3 = aa1;
object o4 = aa2;
Console.WriteLine(a1 == a2);   // True
Console.WriteLine(aa1 == aa2); // True
Console.WriteLine(o1 == o2);   // True
Console.WriteLine(o3 == o4);   // False

Does that make sense?

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
5

For the string type, == compares the values of the strings.

See http://msdn.microsoft.com/en-us/library/53k8ybth.aspx

Regarding your question about addressing, a few lines of code says they will have the same address.

static void Main(string[] args)
{
    String s1 = "hello";
    String s2 = "hello";
    String s3 = s2.Clone() as String;

    Console.Out.WriteLine(Get(s1));
    Console.Out.WriteLine(Get(s2));
    Console.Out.WriteLine(Get(s3));

    s1 = Console.In.ReadLine();
    s1 = Console.In.ReadLine();
    s3 = s2.Clone() as String;

    Console.Out.WriteLine(Get(s1));
    Console.Out.WriteLine(Get(s2));
    Console.Out.WriteLine(Get(s3));
}

public static string Get(object a)
{
    GCHandle handle = GCHandle.Alloc(a, GCHandleType.Pinned);
    IntPtr pointer = GCHandle.ToIntPtr(handle);
    handle.Free();
    return "0x" + pointer.ToString("X");
}

Results in the same address for each set of tests.

Get() courtosey of Memory address of an object in C#

Community
  • 1
  • 1
Babak Naffas
  • 12,395
  • 3
  • 34
  • 49
  • How does memory allocation happens in heap? Will two different string objects but having the same values point to same memory location or not ??? – Atul Sureka Aug 30 '13 at 01:26
  • Yes, they will have the same address. See the updated answer. – Babak Naffas Aug 30 '13 at 01:33
  • 2
    @AtulSureka in fact 2 different strings can have different addresses, but the `compiler` **optimizes** it so that all the same strings will be allocated at the same address because string is **read only** or immutable. – King King Aug 30 '13 at 01:41
1

String Class has done operator overloading to write custom logic for == operator.

That's why when == is used in case of string it does not compare references but actual value.

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
0

string is reference type, because its does not have default allocation size, but is treated as a value type for sanity reasons, could you image a world were == would not work between to exact string values.

Babak Naffas
  • 12,395
  • 3
  • 34
  • 49
sa_ddam213
  • 42,848
  • 7
  • 101
  • 110
0

Please see https://stackoverflow.com/a/1659107/562036 for more info

It's entirely likely that a large portion of the developer base comes from a Java background where using == to compare strings is wrong and doesn't work. In C# there's no (practical) difference (for strings).

Community
  • 1
  • 1
Jianhong
  • 899
  • 9
  • 11