Greg Greg - 4 months ago 24
C# Question

A const and a string

I often use

String.Empty
for a placeholder, which equates to
""
. So my question, why does a
const
not like
String.Empty
? They compile identically.

// Good
private const string example = "";

// Bad
private const string example = String.Empty;


What in
String.Empty
makes it not able to be used with a
const
.

Answer

String.Empty is not a constant it's only readonly field. And since it's readonly field (which is not known on compile time) it can't be assigned to a constant.

http://referencesource.microsoft.com/#mscorlib/system/string.cs,c9f70a27facb27cf

...
//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.
public static readonly String Empty;