String.Empty, string.Empty and “” in C#
All the three above mentioned codes have the same value in C sharp, the value of an empty string. What is the difference between them and what must be used? Let us discuss
These values are identical such that a comparison of them will return true
.
if (String.Empty == string.Empty == ""){
// This block will be executed
}
String.Empty and string.Empty
“String.Empty” and “string.Empty” are the same. According to the Microsoft Documentation, “string” is the keyword, which is an alias of predefined type in the System namespace. They are completely interchangeable and have the same meaning.
However starting from Visual Studio 2017, I am getting suggestions to use “string” in the place of “String”.
Another important thing to note is that these are not constants but are static readonly.
Double Quotes ( “” )
The empty double quotes differs widely from the other two. Unlike them double quotes is a constant. This allows it to be used in
- Switch cases
- Default Parameters
- Attributes, etc…
string.Empty or String.Empty cannot be used these two circumstances.
For example,
switch(val) {
case "":
// This is valid
break;
case string.Empty:
// This is invalid
case String.Empty:
// This is invalid
}
So what to use?
It really comes down to your preference.
I prefer using string.Empty wherever possible because it helps me avoid a special character or space within the quotes. And I find it more easy to read.