问题
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!
回答1:
Empty
is defined as follows:
public static readonly string Empty
It's not a constant. It's a readonly field.
回答2:
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
回答3:
Default parameter values are required to be constants, but String.Empty is a read only field.
来源:https://stackoverflow.com/questions/23984972/why-cant-i-use-string-empty-as-an-optional-parameter-contrary-to-empty-quotatio