Cannot use String.Empty as a default value for an optional parameter in C# - then what's the point?
Posted
by Mikeyg36
on Stack Overflow
See other posts from Stack Overflow
or by Mikeyg36
Published on 2010-04-23T19:11:05Z
Indexed on
2010/04/23
19:13 UTC
Read the original article
Hit count: 215
I am reading Effective C# by Bill Wagner. In Item 14 - Minimize Duplicate Initialization Logic, he shows the following example of using the new optional parameters feature in a constructor:
public MyClass(int initialCount = 0, string name = "")
Notice that he used ""
instead of string.Empty
. He comments:
You'll note [in an example above] that the second constructor specified "" for the default value on the name parameter, rather than the more customary
string.Empty
. That's becausestring.Empty
is not a compile-time constant. It is a static property defined in the string class. Because it is not a compile constant, you cannot use it for the default value for a parameter.
If we cannot use the string.Empty
static in all situations, then doesn't that defeat the purpose of it? I thought that we would use it to be sure that we have a system-independent means of referring to the empty string. Is my understanding wrong? Thanks.
© Stack Overflow or respective owner