Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Empty versus "" [duplicate]

Tags:

c#

It's not different.

http://msdn.microsoft.com/en-us/library/system.string.empty.aspx:

The value of this field is the zero-length string, "".

In application code, this field is most commonly used in assignments to initialize a string variable to an empty string. To test whether the value of a string is String.Empty, use the IsNullOrEmpty method.


According to Brad Abrams:

As David implies, there difference between String.Empty and “” are pretty small, but there is a difference. “” actually creates an object, it will likely be pulled out of the string intern pool, but still… while String.Empty creates no object… so if you are really looking for ultimately in memory efficiency, I suggest String.Empty. However, you should keep in mind the difference is so trival you will like never see it in your code...

As for System.String.Empty or string.Empty or String.Empty… my care level is low ;-)

Update (6/3/2015):

It has been mentioned in the comments that the above quote from 2003 is no longer true (I assume this is referring to the statement that "" actually creates an object). So I just created a couple of simple console programs in C# 5 (VS 2013):

class Program
{
    static void Main()
    {
        // Outputs "True"
        Debug.WriteLine(string.IsInterned(string.Empty) != null);
    }
}

class Program
{
    static void Main()
    {
        // Outputs "True"
        Debug.WriteLine(string.IsInterned("") != null);
    }
}

This demonstrates that both "" and String.Empty are both interned when your code starts running, meaning that for all practical purposes they are the same..

The most important part of Brad's comment is this:

you should keep in mind the difference is so trival you will like never see it in your code...

That's the bottom line. Choosing between "" and String.Empty is not a performance-based decision. Don't waste a lot of time thinking about it. Choose based on whatever you find more readable, or whatever convention is already being used in your project.


For the most part String.Empty is identical to "" however usually I find its easier to use String.IsNullOrEmpty(str) instead of having to compare str == "" || str == null Also if you are on .NET 4.0 String.IsNullOrWhiteSpace(str) covers even more cases, and is by far the best.


There is no difference. Some prefer to use String.Empty for code readability purposes. Use the one you are comfortable with using.