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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With