Wednesday, 9 August 2017

c# - 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 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


Answer



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.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...