Why was the property string foo = string.Empty included in the BCL? It seems more verbose and no clearer than just using an empty string (string foo = "")
|
|
||||
| show 5 more comments |
|
I can only assume here:
It may also be a throwback to C - an empty string in C is not an empty string. It is a character array whose first character is null (hence, empty), which is not the same as C#. My point here being that in different languages you would represent an empty string in different ways (and they may have different meanings) - having a As opposed to what others say about multiple objects - this is not a problem as any string literal will get interned on compilation. This includes the value of |
|||||||||||
|
|
I'm not 100% sure of the sources where I learned these, but some of the points for using it include:
|
|||||||||||||||||||||
|
|
No object will be created for In the past, people have run tests and String.Empty is this:
|
|||||||||
|
|
It is a matter of optimization of memory consumption and an optimization of string comparison. Every time you're using an empty string in your application, you are allocating a string object containing 0 characters. As for string comparison it can be done by comparing references (pointers) instead of character by character, which is a faster even for empty strings. If you are using many times the same string in your application you can use the same kind of mechanism by calling String.Intern() with your string. But if you are using each string only once, then you'll only use more memory. So String.Empty is only a special case optimization which is worth to do for most .Net applications, that's why it was integrated in the BCL. For more detail on this subject I strongly recommend reading Eric Lippert's blog post. You should also take a look at this documentation referenced by his blog post. |
|||||||||||||||||
|
typeof(string).GetField("Empty").SetValue(null, " ");;) – Mason Wheeler Jan 17 '12 at 18:36