A couple of weeks ago, I was asked a C# question in a job interview. The question was exactly this:
string a = "Hello, ";
for(int i = 0; i < 99999999; i++)
{
a += "world!";
}
I was asked exactly, "why this is a bad method for concatenated string?". My response was some sort of "readability, append should be chosen" etc.
But apparently, this is not the case according to the guy that was interviewing me. So, according to him, every time we concatenate a string, because of the structure of CLR, a new reference is created in memory. So, in the end of the following code, we would have 99999999 of string variable "a" in memory.
I thought, the objects are created just once in the stack as soon as a value is assigned to them (I'm not talking about heap). The way I knew was the memory allocation is done once in the stack for each primitive data types, their values are modified as needed and disposed when the execution of a scope is finished. Is that wrong? Or, are new references of variable "a" actually created in the stack every single time it is concatenated?
Can someone please explain how it works for stack? Many thanks.