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.

6
  • @Greg Because it doesn't evaluate to the same thing. Commented Aug 9, 2016 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. Commented Aug 9, 2016 at 19:17
  • @Greg As far as the compiler is concerned, any string value. It has no idea at compile time. Commented Aug 9, 2016 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. Commented Aug 9, 2016 at 19:27
  • 1
    Discussion about preferences between String.Empty vs. ""... This question seem to be just about "why readonly can't be use as const" (approximately stackoverflow.com/questions/755685/static-readonly-vs-const) OR "why String.Empty is not const". Some clarification from Greg may help. Commented Aug 9, 2016 at 20:04

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.