Why is string.Empty
more recommended than ""
?
Is it because when the compiler is parsing the code and a "
comes, the compiler will get ready to read a str开发者_开发技巧ing? but in string.Empty
the compiler will not even get ready to read a string?
There's another reason.
Constants, because of their nature, are a Statics are references to single instances shared by all threads in some application domain, while a literal would end up in producing N
instances of an empty string.
That's why the string.Empty
constant read-only field is recommended over using the empty ""
string literal, and obviously, as others have said, it increases readability.
Anyway, string interning should be taken in account, because under some conditions it might happen that two or more literals containing the same string could end up in a single instance (see remarks section on String.IsInterned
docs):
The common language runtime automatically maintains a table, called the intern pool, which contains a single instance of each unique literal string constant declared in a program, as well as any unique instance of String you add programmatically by calling the Intern method.
No, it most certainly isn't the right answer. You don't mention a language, so let me guess some stuff here:
String.Empty
is a constant defined on class string
.
""
is a string literal for the empty string.
Now, if you are doing equality comparisons, then you want to be sure you're talking about the same object, right?
Does your language guarantee that ""
and string.empty
compare equal? This could also be a question of the runtime. I think the term you want to google is string interning. If you have that, then it doesn't really matter which one you use. If you don't, well, subtle errors will occur.
EDIT: I see you are talking about c#. That does have string interning, so it doesn't really matter which one you use. This is just a matter of style.
if you are using ""
it can be easily mistaken with " "
so to increase readability String.Empty;
can be used
It's basically like a constant value for empty that's more human readable.
精彩评论