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.