Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.Empty vs. "" - Has this changed?

Tags:

c#

According to this answer, "" and string.Empty are very slightly different, in that "" creates an object, whereas string.Empty does not. That answer has the most votes on that question.

However, this answer says that there is no difference. It's a more recent answer as well.

So this was in 2010. Is this really the case? Do string.Empty and "" differ at all, even slightly?

EDIT: This question is meant to be an update to the linked questions, as I found it confusing that no modern answer had been presented, despite some debate on the matter.

like image 464
muttley91 Avatar asked Jun 02 '15 17:06

muttley91


1 Answers

The language specification (C# 4.0) is actually silent on the subject.

According to CLR via C#, it depends entirely on the CLR and not on the C# compiler. A relevant quote from p. 341:

Even if an assembly has this attribute/flag [CompilationRelaxations.NoStringInterning] specified, the CLR may choose to intern the strings, but you should not count on this. In fact, you really should never write code that relies on strings being interned unless you have written code that explicitly calls the String’s Intern method yourself.

So using "" may or may not create an new string object. That depends on the CLR (version) being used. And there's also the possibility that the compiler folds constants, in which case "" would cost 1 object per assembly compilation unit, not per occurrence.

None of this has any relevant impact on memory use or speed, but the clear guideline should be that both ReferenceEquals(s1, "") and ReferenceEquals(s1, String.Empty) should be avoided.

And of course Object.Equals(s1, s2) and s1 == s2 always work fine on strings.

like image 152
Henk Holterman Avatar answered Sep 23 '22 12:09

Henk Holterman