views:

188

answers:

6
string a="I am comparing 2 string";
string b="I am comparing 2 string";

if(a==b)
  return true;
else
  return false;

How does a .NET compiler compare two strings? Does a string work like a struct(int)? string is class so a=b means we are comparing 2 object, but i want to compare 2 values.

A: 

System.String is a class which has the == operator overloaded to compare the content of the strings. This allows it to be "value like" in comparison and yet still be a reference type in other respects.

Daniel Earwicker
A: 

Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive.

C# string

Jonas Elfström
A: 

Strings are compared by the Runtime, not the compiler. Comparison is performed by Equality operator.

Anton Gogolev
+4  A: 

The String class overloads the == operator, so yes it compares the values of the strings, just like comparing value types like int.

(On a side note, the compiler also interns literal strings in the code, so the string variables a and b will actually be referencing the same string object. If you use Object.ReferenceEquals(a,b) it will also return true.)

Guffa
Note that the interning happens on assembly load across the full application domain. http://blogs.msdn.com/cbrumme/archive/2003/04/22/51371.aspx
Lucero
A: 

There are different things to keep in mind here.

First, all identical constant strings will be interned so that both references are equal to start with. Therefore, even if you did a ReferenceEquals() here, you'd get "true" as result. So only for a string built (for instance with a StringBuilder, or read from a file etc.) you'd get another reference and therefore false when doing a reference equality comparison.

If both objects are known to be strings at compile time, the compiler will emit code to compare their value (== overloaded operator on System.String), not their references. Note that as soon as you compare it against an object type reference, this isn't the case anymore.

No runtime check is done to compare a string by value, and the compiler does not emit a .Equals() call for the == operator.

Lucero
A: 

Notice that your question is a little tricky. Because ReferenceEquals will ALSO return true.

This is because of Interning : http://en.wikipedia.org/wiki/String_interning

Cine