Since strings are immutable, do variables with identical string values point to the same string object?
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 op开发者_如何学Pythonerators ( ==, > 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
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
Note the line above where you can force a string to be interned using String.Intern(string)
which then allows you to use object equality instead of string equality for some checks, which is much faster. One example where this is very commonly used is inside the generated XML serializer code along with the name table.
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
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.
精彩评论