user705414
user705414

Reputation: 21200

why cannot declare const static string inside a class

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

Upvotes: 3

Views: 5604

Answers (3)

BoltClock
BoltClock

Reputation: 723498

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.

Upvotes: 20

anishMarokey
anishMarokey

Reputation: 11397

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

Upvotes: 0

Neil Knight
Neil Knight

Reputation: 48537

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

Upvotes: 1

Related Questions