Why can't I use static and const together?

Why can't I use static and const together?

Rate This
  • Comments 8

All constants declarations are implicitly static, and the C# specification states that the (redundant) inclusion of the static modifier is prohibited. I believe this is to avoid the confusion which could occur if a reader were to see two constants, one declared static and one not - they could easily assume that the difference in specification implied a difference in semantics. Having said that, there is no prohibition on redundantly specifying an access modifier which is also the default one, where there is a choice. For instance, a (concrete) method can be explicitly marked as private despite that being the default. The rule appears to be that where there is no choice (e.g. a method declaration in an interface) the redundant modifier is prohibited. Where there is a choice, it's allowed.

[Author: Jon Skeet]

Leave a Comment
  • Please add 6 and 1 and type the answer here:
  • Post
  • I've wrote an article related to this context.

    It can be found here - www.shloemi.com/.../csharp-const-constant-explained-by-faq-qa

  • So effectively, a constant and a static read only field would be the same thing?

  • I think "const" and "static readonly" are not the same. The "const" must be known at compile time. However "static readonly" is initialized at runtime, but its the value cannot be changed (because it's readonly) after initialization.

    In practice, have a look at this example:

    // Trying to assign an instance of a class StorageFolder (which can't be known at compile time) to FOO

    // this will compile

    private static readonly StorageFolder   FOO = KnownFolders.DocumentsLibrary;

    // this won't compile

    private const  StorageFolder            FOO = KnownFolders.DocumentsLibrary;

  • Const must be declared and initialized at compile time. Read only can be initialized at run time and also can be changed, there is no problem with it.

  • So Static Const int=10;

    Is not correct?

  • Really its an awesome explanation that u gave.Hats off....

  • So, constant that is declared using const keyword is always an class field. If we want to have an instance constant field we can use readonly keyword for that constant. Readonly constant can be initialized inside class constructor or inline with declaration. This isn't true for const constants (they are always initialized inline with declaration).

  • From c# language specifications:

    "Even though constants are considered static members, a constant declaration neither requires nor allows a static modifier."

Page 1 of 1 (8 items)