5

Consider the following code snippet in C#

string s = "hi";
object k="hi".Substring(0);

// 1>
k==s // true

// 2>
Object.ReferenceEquals(s,k) //true

but when,

Object k="hii".Substring(0,2);

// 1>
 k==s // false
// 2>
Object.ReferenceEquals(s,k) //false

I am having difficulty understanding why in the first case, the strings were interned while it doesn't happen so in the second case. Also it would be very helpful if anyone can point out the rules when string interning happens in c#.

user3292642
  • 711
  • 2
  • 8
  • 32
dividedbyzero
  • 99
  • 2
  • 5
  • From [the documentation](https://msdn.microsoft.com/en-us/library/hxthx5h6(v=vs.110).aspx): _"If startIndex is equal to zero, the method returns the original string unchanged"_. As far as when interning happens, unless you explicitly ask for a string to be interned at runtime, the only time it happens is at compile time. Your first example works because `Substring(0)` doesn't do anything except return the `string` reference you passed it. – Peter Duniho Apr 04 '17 at 06:30
  • Please note that interning doesn't actually have anything to do with your question. The first example would have worked regardless of whether the original string had been interned or not. You're literally _always_ going to wind up comparing the same `string` reference to itself, if you obtain the second reference by calling `Substring(0)` on the first. – Peter Duniho Apr 04 '17 at 06:36
  • 1
    @PeterDuniho : Did not post the question to waste anyone's time. I just wanted to know why in the 1st case, both strings point to the same memory location, while in the second case they refer to different memory location. Obviously what I missed was that "If startIndex is equal to zero, the method returns the original string unchanged" – dividedbyzero Apr 04 '17 at 06:59
  • @Damien_The_Unbeliever : How is this question exact duplicate of the other question? – dividedbyzero Apr 04 '17 at 07:01
  • 1
    @PeterDuniho I would be more careful in the future, after all this is just my first question. I got the Substring scenario. Would you be kind enough to point out the rules of interning? – dividedbyzero Apr 04 '17 at 07:09
  • See additional duplicate links above. One even includes [an answer](http://stackoverflow.com/a/34729514) that touches on what your _real_ question was (i.e. the behavior of `Substring()`). See [Does String.Replace() create a new string if there's nothing to replace?](http://stackoverflow.com/a/27052744) for an answer that focuses more specifically on these degenerate (i.e. "no operation") scenarios. – Peter Duniho Apr 04 '17 at 07:23
  • @PeterDuniho Thank you. Now I believe I got what I wanted to know. – dividedbyzero Apr 04 '17 at 07:41

0 Answers0