5

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.

George Stocker
  • 57,289
  • 29
  • 176
  • 237
Greg
  • 11,302
  • 2
  • 48
  • 79
  • @Greg Because it doesn't evaluate to the same thing. – Servy Aug 09 '16 at 19:16
  • 3
    I would suspect it's because `Empty` isn't *itself* a constant, so as far as the compiler is concerned it *could* resolve to anything. And a `const` needs to guarantee at compile time what it's value will be. The literal `""` provides that guarantee. – David Aug 09 '16 at 19:17
  • @Greg As far as the compiler is concerned, any string value. It has no idea at compile time. – Servy Aug 09 '16 at 19:17
  • 2
    @Lucas There are millions of ways to subtly break code when you have a malicious developer. String.Empty is no exception to this; a malicious developer could just as easily edit the string that it refers to to a non-empty string (yes, it would *absolutely* be possible, even through managed code). There's virtually no way to defend code against a malicious developer editing the source code; it's not even something you can meaningfully attempt to defend against. – Servy Aug 09 '16 at 19:27
  • We're using String.Empty instead of "". It just looks better IMHO. – Mårten Wikström Aug 09 '16 at 19:58
  • 1
    Discussion about preferences between [`String.Empty` vs. `""`](http://stackoverflow.com/questions/151472/what-is-the-difference-between-string-empty-and-empty-string)... This question seem to be just about "why readonly can't be use as const" (approximately http://stackoverflow.com/questions/755685/static-readonly-vs-const) OR ["why `String.Empty` is not const"](http://stackoverflow.com/questions/507923/why-isnt-string-empty-a-constant). Some clarification from Greg may help. – Alexei Levenkov Aug 09 '16 at 20:04

1 Answers1

9

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;
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215