Pankaj
Pankaj

Reputation: 4505

How does .NET compiler compare two strings?

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.

Upvotes: 1

Views: 1115

Answers (6)

Cine
Cine

Reputation: 4402

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

Upvotes: 0

Lucero
Lucero

Reputation: 60190

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.

Upvotes: 0

Guffa
Guffa

Reputation: 700302

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.)

Upvotes: 4

Anton Gogolev
Anton Gogolev

Reputation: 115731

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

Upvotes: 0

Jonas Elfström
Jonas Elfström

Reputation: 31428

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

Upvotes: 0

Daniel Earwicker
Daniel Earwicker

Reputation: 116674

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.

Upvotes: 0

Related Questions