Why isn't String.Empty a constant?
Solution 1:
The reason that static readonly
is used instead of const
is due to use with unmanaged code, as indicated by Microsoft here in the Shared Source Common Language Infrastructure 2.0 Release. The file to look at is sscli20\clr\src\bcl\system\string.cs
.
The Empty constant holds the empty string value. We need to call the String constructor so that the compiler doesn't mark this as a literal.
Marking this as a literal would mean that it doesn't show up as a field which we can access from native.
I found this information from this handy article at CodeProject.
Solution 2:
I think there is a lot of confusion and bad responses here.
First of all, const
fields are static
members (not instance members).
Check section 10.4 Constants of the C# language specification.
Even though constants are considered static members, a constant-declaration neither requires nor allows a static modifier.
If public const
members are static, one could not consider that a constant will create a new Object.
Given this, the following lines of code do exactly the same thing in respect to the creation of a new Object.
public static readonly string Empty = "";
public const string Empty = "";
Here is a note from Microsoft that explains the difference between the 2:
The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants, ...
So I find that the only plausible answer here is Jeff Yates's.