Why can't I use string.Empty as an optional parameter contrary to empty quotation marks? [duplicate]

元气小坏坏 提交于 2020-01-03 11:02:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!