-2

I've encountered with the following code riddle:

string a = "S1";
string b = "S2";
a = a+b;

What will stay in the memory after this:

  1. "S1S2", "S2"
  2. "S1", "S1S2"
  3. "S1", "S2", "S1S2"

What is your opinion? And why, in my opinion (c)

  • string a pointing to "S1S2"
  • string b pointing to "S2"
  • And "S1" is also in the background even after changing pointer/reference of string a
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
CSharper
  • 769
  • 2
  • 7
  • 13

1 Answers1

5

I think c is correct answer, but the reason does not match yours.

You have to be aware of intern pool:

The common language runtime automatically maintains a table, called the intern pool, which contains a single instance of each unique literal string constant declared in a program, as well as any unique instance of String you add programmatically by calling the Intern method.

String.IsInterned Method

And that's why both S1 and S2 will be within intern pool even if there is no reference to them.

And why S1S2 will be in memory is quite obvious - a points to that string.

Community
  • 1
  • 1
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263