In .NET, what is the difference between String.Empty and "", and are they interchangable, or is there some underlying reference or Localization issues around equality that String.Empty will ensure are not a problem?
In .Net pre 2.0, ""
creates an object while String.Empty
creates no object. So it is more efficient to use String.Empty.
.Length == 0
is the fastest option, but .Empty
makes for slightly cleaner code.
As @chadmyers mentioned, in version 2.0 and above of .Net, all occurrences of ""
refer to the same string literal.
So ""
is pretty equivalent to .Empty
, but still not as fast as .Length == 0
.
String.Empty does not create an object whereas "" does. The difference, as pointed out here, is trivial, however.
It just doesn't matter!
Some past discussion of this:
http://www.codinghorror.com/blog/archives/000185.html
All instances of "" are the same, interned string literal (or they should be). So you really won't be throwing a new object on the heap every time you use "" but just creating a reference to the same, interned object. Having said that, I prefer string.Empty. I think it makes code more readable.
There appears to be some debate over whether there is a difference at all between String.Empty and "".
There is universal agreement, however, that if there is a difference, it is much too trivial to be concerned with.
The previous answers were correct for .NET 1.1 (look at the date of the post they linked: 2003). As of .NET 2.0 and later, there is essentially no difference. The JIT will end up referencing the same object on the heap anyhow.
According to the C# specification, section 2.4.4.5: http://msdn.microsoft.com/en-us/library/aa691090(VS.71).aspx
Each string literal does not necessarily result in a new string instance. When two or more string literals that are equivalent according to the string equality operator (Section 7.9.7) appear in the same assembly, these string literals refer to the same string instance.
Someone even mentions this in the comments of Brad Abram's post
In summary, the practical result of "" vs. String.Empty is nil. The JIT will figure it out in the end.
I have found, personally, that the JIT is way smarter than me and so I try not to get too clever with micro-compiler optimizations like that. The JIT will unfold for() loops, remove redundant code, inline methods, etc better and at more appropriate times than either I or the C# compiler could ever anticipate before hand. Let the JIT do its job :)
The above answers are technically correct, but what you may really want to use, for best code readability and least chance of an exception is String.IsNullOrEmpty(s)
String.Empty is a readonly field while "" is a const. This means you can't use String.Empty in a switch statement because it is not a constant.