Note that there are some explanatory texts on larger screens.

plurals
  1. POCannot use String.Empty as a default value for an optional parameter
    primarykey
    data
    text
    <p>I am reading <strong>Effective C#</strong> by Bill Wagner. In <em>Item 14 - Minimize Duplicate Initialization Logic</em>, he shows the following example of using the new optional parameters feature in a constructor:</p> <p><code>public MyClass(int initialCount = 0, string name = "")</code></p> <p>Notice that he used <code>""</code> instead of <code>string.Empty</code>.<br> He comments:</p> <blockquote> <p>You'll note [in an example above] that the second constructor specified "" for the default value on the <em>name</em> parameter, rather than the more customary <code>string.Empty</code>. That's because <code>string.Empty</code> 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. </p> </blockquote> <p>If we cannot use the <code>string.Empty</code> 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.</p> <p>UPDATE<br> Just a follow up comment. According to MSDN:</p> <blockquote> <p>Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used. <strong>Default values must be constants.</strong></p> </blockquote> <p>Then we aren't be able to use <code>System.Environment.NewLine</code> either, or use newly instantiated objects as default values. I haven't used VS2010 yet, and this is disappointing!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload