Cris
Cris

Reputation: 317

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

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

Answers (4)

Suhas Parameshwara
Suhas Parameshwara

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

stud3nt
stud3nt

Reputation: 2143

You can also use string.Empty which is more readable. It has nothing to do with performance.

Upvotes: 1

Damon Quire
Damon Quire

Reputation: 130

The second one is redundant. It's already a string. So the first one would be the best option.

Upvotes: 6

Panagiotis Kanavos
Panagiotis Kanavos

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

Related Questions