1

Consider the following code in C#:

String a = "hello world";
List<String> ListA = new List<String>();
List<String> ListB = new List<String>();
ListA.Add(a);
ListB.Add(a);

My question is: are the two strings in the two lists are actually pointing to the same location in memory? In other words, the additional memory in having multiple containers for the same string is only about references(pointers) not actual memory of the strings?

Thanks.

Yajun Wang
  • 13
  • 2
  • [string.Intern](https://msdn.microsoft.com/en-us/library/system.string.intern(v=vs.110).aspx) – Steve Nov 18 '15 at 18:55

2 Answers2

3

In your code, a is a reference to a string. Adding the same reference to both lists will reference the same memory location.

Jacob Krall
  • 28,341
  • 6
  • 66
  • 76
0

My question is: are the two strings in the two lists are actually pointing to the same location in memory?

Yes, they are. The fact that you added the same string twice and now both lists have a reference to it doesn't change the fact there's a single instance of the said string.

Another factor is that you're creating a string literal, which will be interned onto the string pool. This will make any other creation of the same string re-use the already allocated string instead of allocating a new one.

From the documentation of string.Intern:

The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program. Consequently, an instance of a literal string with a particular value only exists once in the system.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321