What is the difference between String.Empty and "" (empty string)?
what is the difference between String.Empty and "", and are they interchangable
string.Empty
is a read-only field whereas ""
is a compile time constant. Places where they behave 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: // Error: A constant value is expected.
break;
case "":
break;
}
Attribute arguments
[Example(String.Empty)]
// Error: An attribute argument must be a constant expression, typeof expression
// or array creation expression of an attribute parameter type
In .NET prior to version 2.0, ""
creates an object while string.Empty
creates no objectref, which makes string.Empty
more efficient.
In version 2.0 and later of .NET, all occurrences of ""
refer to the same string literal, which means ""
is equivalent to .Empty
, but still not as fast as .Length == 0
.
.Length == 0
is the fastest option, but .Empty
makes for slightly cleaner code.
See the .NET specification for more information.