Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is String.Empty an invalid default parameter?

If I type the following:

public Response GetArticles(string Filter = String.Empty)
{
    //Body
}

Visual Studio gives me this error:

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

If I change the String.Empty to the classic "" it is fixed.

But I'm still curious about what is wrong with the String.Empty and its behavior.

like image 592
Miguel A. Arilla Avatar asked Jul 15 '26 08:07

Miguel A. Arilla


1 Answers

Why is String.Empty an invalid default parameter?

Because "Default parameter value for 'Filter' must be a compile-time constant". And String.Empty is not a constant but only static readonly. String literals like "Foo" are constants as implementation detail(i haven't found documentation).

Further read: Why isn't String.Empty a constant?

Quote from 10.4 Constants of the C# language specification:

The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants

Here is the MSDN quote according to optional parameters:

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.

I'm suprised that you can use new ValType(), where ValType is a value type or struct. I didn't know that you can use the default constructor like new DateTime() but not new DateTime(2015,1,15). Learned something new from my own answer.

like image 154
Tim Schmelter Avatar answered Jul 17 '26 22:07

Tim Schmelter