6

I'm refining my code and noticed that at some places I had optional parameters with the default value of an empty string. I changed that to a default value from the class for empty string and guess what! Apparently there's a difference between empty quotation marks and string.Empty. What the duck?! (typo intended)

private void Khaboom(String parameter = "") { ... }

private void Bazinga(String parameter = String.Empty) { ... }

Can someone explain to me why the duck does Khaboom work while Bazinga doesn't?!

The error message whines this:

Default parameter value for 'parameter' must be a compile-time constant.

Well... It is!

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438

3 Answers3

13

Empty is defined as follows:

public static readonly string Empty

It's not a constant. It's a readonly field.

spender
  • 117,338
  • 33
  • 229
  • 351
  • 6
    And for those wondering why it is not a constant, there might actually be a [very good reason for that](http://www.stum.de/2009/01/14/const-strings-a-very-convenient-way-to-shoot-yourself-in-the-foot/). – Doctor Blue Jun 01 '14 at 22:08
  • @Scott... I did wonder... thx. – spender Jun 01 '14 at 22:10
  • @Scott Your link gives absolutely no good reason why `string.Empty` was not chosen to be a `const` field. The reason is much more obscure. There are threads on this topic here on Stack Overflow. – Jeppe Stig Nielsen Jun 01 '14 at 22:22
  • @JeppeStigNielsen: Where? – spender Jun 01 '14 at 22:24
  • http://stackoverflow.com/questions/507923/why-isnt-string-empty-a-constant – Jeroen Vannevel Jun 01 '14 at 22:25
  • Note that the old (problematic?) decision to not make `string.Empty` a literal, was possibly compensated for with the .NET 4.5 version. Actually, since 4.5, when you read from `string.Empty`, with IL code created by the C# compiler for instance, the runtime ["cheats"](http://stackoverflow.com/questions/16618302/) and substitutes an empty string instead of reading the actual string reference held by the static field. This optimization appears to make `string.Empty` more const-like when the code runs. But at compile-time it is still not a true constant, of course, so the above answer is correct. – Jeppe Stig Nielsen Jun 01 '14 at 22:36
4

A default value must be one of the following types of expressions:

  • a constant expression;
  • an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;
  • an expression of the form default(ValType), where ValType is a value type.

Since string.Empty is neither of these things, it is not allowed.

http://msdn.microsoft.com/en-us/library/dd264739.aspx

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
2

Default parameter values are required to be constants, but String.Empty is a read only field.

Richard Szalay
  • 83,269
  • 19
  • 178
  • 237