开发者

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 (e.g. 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜