Simullacra
Simullacra

Reputation: 175

Does C# implicitly allocate an empty string when a non-empty string is declared?

I'm concerned with a comment on a previous answer that dates back to 2011: Immutable strings.

It's claimed there that this code

string str="a";
str +="b";
str +="c";
str +="d";
str +="e";

console.write(str) //output: abcde

creates 10 strings in memory:

"", "a", "b", "c", "d", "e", "ab", "abc", "abcd", and "abcde"

While I can get why this happens, I still can't grasp why there is a "" string in the first place. Can someone hint me on this? Maybe that's even not the case? C# documentation doesn't shed any light on the issue. My only guess here is that C#'s string is a ref type, so it's null by default, but like...in this example it gets a value at the very beginning, so I'm kinda perplexed.

Upvotes: 4

Views: 217

Answers (1)

Matthew Watson
Matthew Watson

Reputation: 109557

The answer is: No, it doesn't.

If you decompile the code generated for a release build you'll see something like this:

private static void Main()
{
    Console.WriteLine(string.Concat(string.Concat(string.Concat(string.Concat("a", "b"), "c"), "d"), "e"));
}

The IL generated for this code is:

IL_0000: ldstr "a"
IL_0005: ldstr "b"
IL_000a: call string [mscorlib]System.String::Concat(string,  string)
IL_000f: ldstr "c"
IL_0014: call string [mscorlib]System.String::Concat(string,  string)
IL_0019: ldstr "d"
IL_001e: call string [mscorlib]System.String::Concat(string,  string)
IL_0023: ldstr "e"
IL_0028: call string [mscorlib]System.String::Concat(string,  string)
IL_002d: call void [mscorlib]System.Console::WriteLine(string)
IL_0032: ret

As you can see, there is no use of an empty string there.

(The code generated is slightly different for a debug build, in order to better support the debugger, but it still doesn't create an empty string.)

Upvotes: 5

Related Questions