Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing consts in static classes
    text
    copied!<p>I was plugging away on <a href="http://code.google.com/p/noda-time/" rel="noreferrer">an open source project</a> this past weekend when I ran into <a href="http://code.google.com/p/noda-time/source/browse/src/NodaTime/Format/FormatUtils.cs" rel="noreferrer">a bit of code that confused me</a> to look up the usage in the <a href="http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx" rel="noreferrer">C# specification</a>.</p> <p>The code in questions is as follows:</p> <pre><code>internal static class SomeStaticClass { private const int CommonlyUsedValue = 42; internal static string UseCommonlyUsedValue(...) { // some code value = CommonlyUsedValue + ...; return value.ToString(); } } </code></pre> <p>I was caught off guard because this appears to be a non static field being used by a static function which some how compiled just fine in a static class!</p> <p>The specification states (§10.4):</p> <blockquote> <p>A constant-declaration may include a set of attributes (§17), a new modifier (§10.3.4), and a valid combination of the four access modifiers (§10.3.5). The attributes and modifiers apply to all of the members declared by the constant-declaration. <strong>Even though constants are considered static members, a constant-declaration neither requires nor allows a static modifier.</strong> It is an error for the same modifier to appear multiple times in a constant declaration.</p> </blockquote> <p>So now it makes a little more sense because <em>constants are considered static members</em>, but the rest of the sentence is a bit surprising to me. Why is it that <em>a constant-declaration neither requires nor allows a static modifier</em>? Admittedly I did not know the spec well enough for this to immediately make sense in the first place, but <strong>why was the decision made to not force constants to use the static modifier if they are considered static?</strong></p> <p>Looking at the last sentence in that paragraph, I cannot figure out if it is regarding the previous statement directly and there is some implicit static modifier on constants to begin with, or if it stands on its own as another rule for constants. Can anyone help me clear this up?</p>
 

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