Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String interning and equality operators

Tags:

string

.net

I was just reading this site which states: Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references...a and b do not refer to the same string instance ( http://msdn.microsoft.com/en-us/library/362314fe.aspx ).

I haven't checked the internals of the String class, but is that statement correct? From what I understand, the reason a String is immutable is due to string interning. In other words, only one copy of a string is stored for each unique value. All String variables with identical values reference the same object. I thought that was why "a" == "a" works -- not because it is defined to compare the values. If it were checking the value, then the strings would have to be compared character by character, causing significant performance considerations, and eliminating one of the main reasons to use string interning to begin with.

Maybe they over-simplified, but I think it's misleading to suggest that the String equality operators have been defined differently than other reference types. Please do correct me if I'm wrong!

like image 524
Nelson Rothermel Avatar asked Feb 24 '23 12:02

Nelson Rothermel


1 Answers

String can be interned, but they don't have to be. String literals are interned (by default - this can be changed with the CompilationRelaxations.NoStringInterning attribute now), and instances created at runtime could be, but in general aren't unless special steps are taken (like calling String.Intern()).

There can be multiple instances of stings that have the same value.

Also, there are reasons besides being able to intern strings that they're immutable - immutability is mainly so objects holding references don't have to worry about those values changing 'behind their backs'. So it's more along the lines of being able to inter strings is a consequence of immutability, rather than strings must be immutable so we can intern them.

like image 111
Michael Burr Avatar answered Mar 03 '23 19:03

Michael Burr