Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between initialize a string to "" or to "".ToString() - Which one should I use?

Tags:

c#

How should I initialize an empty string in C# and why? Which one is faster?

string myString = "";

or

string myString = "".ToString();
like image 789
Cris Avatar asked Dec 02 '22 09:12

Cris


1 Answers

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

like image 114
Panagiotis Kanavos Avatar answered Dec 05 '22 01:12

Panagiotis Kanavos