string.empty vs. ""

  • Thread starter Thread starter Ole Hanson
  • Start date Start date
O

Ole Hanson

Hi

I am wondering if there is any programmatic difference between the
String.Empty and the "" for declaring an empty string?

Furthermore, is there any performance penalty by doing the one over the
other?


/Ole
 
Looks like there is no difference as it is just a field that holds an empty
string. There probably is no noticable different in performance since
String.Empty is simply a field.

static String()
{
string.Empty = "";
...}
 
Ole said:
Hi

I am wondering if there is any programmatic difference between the
String.Empty and the "" for declaring an empty string?
No.

Furthermore, is there any performance penalty by doing the one over
the other?

I'd be surprised if that was the case. I assume String.Empty exists
primarily to enhance readability -- but certainly not everybody likes it (I
do, though).

Cheers,
 
Correct me if I'm wrong

But, I thought there was a difference.

S1 = "";
S2 = "";

Doesn't this create 2 "different" string instances.

S1 = String.Empty;
S2 = String.Empty;

Doesn't this refer twice to same static instance?

This is a very important, especially when using a lot of strings. Perhaps
the compiler solves this.

Kind regards

Alexander
 
Alexander said:
Correct me if I'm wrong

But, I thought there was a difference.

S1 = "";
S2 = "";

Doesn't this create 2 "different" string instances.

No, not like this.
S1 = String.Empty;
S2 = String.Empty;

Doesn't this refer twice to same static instance?
Yes.

This is a very important, especially when using a lot of strings.
Perhaps the compiler solves this.

See section 2.4.4.5 of the C# language spec:

Each string literal does not necessarily result in a new string instance.
When two or more string literals that are equivalent according to the string
equality operator [...] appear in the same assembly, these string literals
refer to the same string instance.

Cheers,
 
Back
Top