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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With