-4

I know string is an alias of System.String but I am unable to understand this specific behavior.

string s = "ABC";
string s1 = "AB"+"C";
String s2 = new String("ABC");

s == s1 returns true but s == s2 returns false.

I know string is a reference type so the instance of s and s1 refers two different instances but why is s==s1 true?

bfontaine
  • 18,169
  • 13
  • 73
  • 107
shujaat siddiqui
  • 1,527
  • 1
  • 20
  • 41
  • 1
    Possible duplicate of [Are string.Equals() and == operator really same?](http://stackoverflow.com/questions/3678792/are-string-equals-and-operator-really-same) – Eugene Podskal Jan 21 '17 at 14:55
  • 1
    http://stackoverflow.com/questions/7074/what-is-the-difference-between-string-and-string-in-c – Khoshtarkib Jan 21 '17 at 14:56
  • 1
    "AB"+"C" is turned into "ABC" by the compiler. And because strings are interned, s and s1 are references to the same string. The string type is special and is treated differently than other references types. – Dennis_E Jan 21 '17 at 15:02
  • The more interesting question is why `s==s2 ` returns false. – Peter - Reinstate Monica Jan 21 '17 at 15:08
  • 4
    The code you present does not compile with VS 2013. The line `String s2 = new String("ABC");` results in `Error 1 The best overloaded method match for 'string.String(char*)' has some invalid arguments` and `Error 2 Argument 1: cannot convert from 'string' to 'char*'` – Peter - Reinstate Monica Jan 21 '17 at 15:13
  • 1
    Why don't you present a complete little program and its original output? That would force you to fix your error and make it easier to examine the code. As it stands, it's a downvote for lacking research effort and sloppy presentation (which is inexcusable in programming). – Peter - Reinstate Monica Jan 21 '17 at 17:05
  • `new String("ABC");` is only equal to a compiler error. Don't base questions on imaginary code. – H H Jan 21 '17 at 18:17

1 Answers1

3

why is s==s1 true ?

This question has been answered before — operator==() has been overridden for strings in order to avoid the commonplace mistakes which would otherwise happen.

More interesting is the question why after String s2 = new String("ABC");, allegedly "s==s2 return false".

Well, the line as presented does not compile. What compiles is String s2 = new String( new char[] { 'A', 'B', 'C'});, after which s==s2 is true.

Note that string is simply a C# keyword, an alias for System.String; the two can be used interchangeably without changing the meaning of a program.

Peter - Reinstate Monica
  • 15,048
  • 4
  • 37
  • 62