This code is not valid:
private void Foo(string optionalString = string.Empty)
{
// do foo.
}
But this code is:
private void Foo(string optionalString = "")
{
// do foo.
}
Why? Because string.Empty is a readonly field, not a constant, and defaults for optional parameters must be a compile-time constant.
So, onto my question... (well, concern)
This is what i've had to do:
private const string emptyString = "";
private void Foo(string optionalString = emptyString)
{
// do foo.
if (!string.IsNullOrEmpty(optionalString))
// etc
}
How do you guys handle optional string parameters?
Why can they not make String.Empty a compile-time constant?
nullString
a confusing name, because at first glance I would be inclined to think it wasnull
, not""
. As for your final question, see [ Why isn't String.Empty a constant? ](#508423). @Dave, there's no Unicode thing, here.""
is fine; see also [ In C#, should I use string.Empty or String.Empty or “” ? ](#263691). – Murrhine