why cannot declare const static string inside a class

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


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.


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 (eg a method declaration in an interface) the redundant modifier is prohibited. Where there is a choice, it's allowed.

Taken from here


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

链接地址: http://www.djcxy.com/p/21230.html

上一篇: AutomationProperties.Name VS x:名称

下一篇: 为什么不能在类中声明const静态字符串