Andyz Smith
Andyz Smith

Reputation: 708

Can two identical strings ever object compare to different instances?

Section 7.10.7 of C# Programming Language (A. Hejlsberg, et. al, 2011 Fourth Edition, Annotated for 4.0 ) states that, " When two separate string instances contain the exact same sequences of characters, the values of the strings are equal, but the references are different."

Is this ever the run-time case? Won't the .NET runtime and BCL ALWAYS intern two identical strings to the same reference box?

I understand the book is talking about a 'spec', but the next question - is there ANY known implementation of C# that behaves this way?

EDIT

OK what's really bothering me is this:

String FirstOne = "StatusOK"
String MiddleOne = "StatusOK"
String LastOne = "StatusOK"

Integer FindMeOne(object AnythingtoFind) { return MsgLst.IndexOf(AnythingToFind) }

List<String> MsgLst;
MsgLst.Add(FirstOne);
MsgLst.Add(MiddleOne);
Msglst.Add(LastOne);

Integer foo = FindMeOne( LastOne );

I don't expect foo to be 1! I guess I'm just silly that way.

UPDATE All I have to do to get what I want is:

public class MyNiceStringsThatICanFind 
{ 
private String foobar;
}

But again this is not nice. If objects track themselves by HashCode, what is so stinking special about a string? Why doesn't the runtime look at your Objects and see, hey, maybe it is the exact same thing inside, let's make it the same reference.

Upvotes: 1

Views: 187

Answers (1)

Lee
Lee

Reputation: 144206

This equality behaviour only applies to string literals (although see NoStringInterning). If you create equal strings at runtime they will not necessarily refer to the same instance:

var abc = "abc";
var ab = "ab";
var c = "c";

var abc2 = ab + c;
bool eq = Object.ReferenceEquals(abc, abc2);  //false

var interned = String.Intern(abc2);
bool ieq = Object.ReferenceEquals(interned, abc);  //true

Upvotes: 1

Related Questions