What is the difference between String.Empty and “” and null?

Use null when you want to represent that there is no value;
Use String.Empty when you want to represent that there is a value, but the value is a blank string.
======================================================================
String.Empty because it is a static variable, rather than “” which has to create a new string, and null means that you must then set the string equal to a new instance of a string.

======================================================================

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.

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 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.

string.Empty is a read-only field whereas "" is a compile time constant. Two places where I have seen them behaving differently are:

Default Parameter value in C# 4.0 or higher

void SomeMethod(int ID, string value = string.Empty)
 //Error - Default parameter value for 'value' must be a compile-time constant
{
    //... implementation
}

Case expression in switch statement.

string str = "";
switch(str)
{
    case string.Empty: // A constant value is expected. 
        break;

    case "":
        break;

}

======================================================================

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s