Question

I read somewhere that if you have multiple strings in your application that are the same, that there is really only ever one created and all references really point to the same string.

I see warnings about this behavior when reading about locks. Like never lock on string because any other lock anywhere in the application could potentially lock on the same string. Especially if you locked on :

string lockObj = "";
...
{
  lock(lockObj){
  ...
  }
}

So this brings me back to there only ever being a single copy of a specific string. So if I wanted to compare two strings, is there any way to do it by their memory location? Like..

public bool areSame(string s1,string s2){
   return &s1 == &s2;
}

Thanks for the help!

Was it helpful?

Solution

I read somewhere that if you have multiple strings in your application that are the same, that there is really only ever one created and all references really point to the same string.

That is incorrect. Although you can arrange your program in such a way that it used a single object per unique string, .NET does not make such guarantee. It is true that C# compiler will make all string objects produced from string literals in your program point to the same string object. However, it is rather easy to create multiple string objects with identical content.

if I wanted to compare two strings, is there any way to do it by their memory location?

You can use Object.ReferenceEquals method for that:

public bool areSame(string s1,string s2){
   return Object.ReferenceEquals(s1, s2);
}

OTHER TIPS

You could use the Object.ReferenceEquals Method

According to MSDN: Determines whether the specified Object instances are the same instance.

var x = "a";
x+= "b";
var y = "ab";
Console.WriteLine(x==y);
Console.WriteLine(object.ReferenceEquals(x, y));

You'll see that the second one returns false (i.e. they are in 2 different memory locations)

Why did I need to assign x the way I did? Well because .net automatically interns all string literals.. Which means all identical string literals actually do point to the same location in memory

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top