tags:

views:

212

answers:

3

a)

        string s  = "value";
        string s1 = "value";

Do s and s1 reference variables point to same string object ( I’m assuming this due to the fact that strings are immutable )?

b) I realize equality operators ( ==, > etc ) have been redefined to compare the values of string objects, but is the same true when comparing two strings using static methods Object.Equals() and Object.ReferenceEquals()?

thanx

+3  A: 

Yes, these will point to the same string, because they're both defined as string literals. If you create a string programatically, you'd have to manually intern the string.

This is because the .NET framework interns the string literals in your program into the intern pool. You can use String.Intern to retrieve this reference, or to manually intern your own, runtime-generated string.

For more details, refer to the docs for Intern:

Consequently, an instance of a literal string with a particular value only exists once in the system.

For example, if you assign the same literal string to several variables, the runtime retrieves the same reference to the literal string from the intern pool and assigns it to each variable

Reed Copsey
However, this is by implementation, not specification.
NickLarsen
True - but the implementation does do this, currently, for literal values.
Reed Copsey
I added some clarification in my answer.
Reed Copsey
+2  A: 

With the current CLR identical literal strings do point to the same actual objects. The process is called interning and applies to all compile time strings.

Strings created at runtime are not interned per default, but can be added to the interned collection by calling string.Intern.

Please see my answer for this question for a detailed explanation of how .NET strings are stored.

Brian Rasmussen
+18  A: 

No, not all strings with the same value are the same object reference.

Strings generated by the compiler will all be Interned and be the same reference. Strings generated at runtime are not interned by default and will be different references.

var s1 = "abc";
var s2 = "abc";
var s3 = String.Join("", new[] {"a", "b", "c"});
var s4 = string.Intern(s3); 
Console.WriteLine(ReferenceEquals(s1, s2)); // Returns True
Console.WriteLine(ReferenceEquals(s1, s3)); // Returns False
Console.WriteLine(s1 == s3); // Returns True
Console.WriteLine(ReferenceEquals(s1, s4)); // Returns True
Sam
+1 for clarifying that strings created at run-time have to manually be interned.
ChaosPandion
It might be worthwhile to add var s4 = string.Intern(s3); Console.WriteLine(ReferenceEquals(s1, s4)); // Returns True
Dolphin
@Dolphin, good point, I updated the answer.
Sam
thank you all for your input
AspOnMyNet