3

why cannot declare const static string inside a class? Have to use static readonly

user705414
  • 20,472
  • 39
  • 112
  • 155
  • This question is a duplicate of http://stackoverflow.com/questions/2631975/c-using-consts-in-static-classes/2632844#2632844 Also see my article on the subject for details: http://blogs.msdn.com/b/ericlippert/archive/2010/06/10/don-t-repeat-yourself-consts-are-already-static.aspx – Eric Lippert May 05 '11 at 15:11

3 Answers3

20

In the C# language (as well as PHP), const is implicitly static, so you don't use both keywords together. This is unlike C and C++ where const doesn't say if a variable is static or not, just that its value is not modifiable.

You declare a constant string like this:

const string SomeConstant = "abc";

There's a slight difference between const fields and static readonly fields too, but both are similar in that you can't change their values. Details are in this question.

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
1

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.

Taken from here

Neil Knight
  • 47,437
  • 25
  • 129
  • 188
0

I have written a blog on this, which will give you a better understanding.Have a look http://anishmarokey.blogspot.com/2009/09/const-vs-fields.html

mostly primitive types used as Constant other as static readonly

anishMarokey
  • 11,279
  • 2
  • 34
  • 47