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!

2
  • 1
    @MichaelPerrenoud Duplicated what? Commented Jun 1, 2014 at 22:14
  • I marked it as a duplicate but then reopened it. Commented Jun 1, 2014 at 22:15

3 Answers 3

13

Empty is defined as follows:

public static readonly string Empty 

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

Sign up to request clarification or add additional context in comments.

6 Comments

And for those wondering why it is not a constant, there might actually be a very good reason for that.
@Scott... I did wonder... thx.
@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.
@JeppeStigNielsen: Where?
|
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

1 Comment

s/neither of these things/none of these things
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.