问题
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.
回答1:
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.
回答2:
string.Empty
is not a compile time constant. You can for example change it's value using Reflection
. but ""
empty string literal is constant and it's value is known at compile time so that's why it is valid.
来源:https://stackoverflow.com/questions/28043397/why-is-string-empty-an-invalid-default-parameter