Reputation: 317
How should I initialize an empty string in C# and why? Which one is faster?
string myString = "";
or
string myString = "".ToString();
Upvotes: 4
Views: 154
Reputation: 1454
Please use the first one which is the best option
string myString = "";
You can also use string.Empty in C#
string myString = string.Empty;
The second one is pointless because "" which is already a string and converting string("").ToString() is pointless.
Upvotes: 2
Reputation: 2143
You can also use
string.Empty
which is more readable. It has nothing to do with performance.
Upvotes: 1
Reputation: 130
The second one is redundant. It's already a string
. So the first one would be the best option.
Upvotes: 6
Reputation: 131219
String.ToString() just returns the string itself :
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
return this;
}
Which means string myString = "".ToString()
is pointless. After all, it's already a string
In fact, given that strings are immutable and, in this case, interned, ""
is the same string instance returned by String.Empty
Upvotes: 9