Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I access a public const in c#?

Tags:

c#

I have something like this:

namespace MyNamespace {    

    public partial class MyClass: UserControl {

        public static const String MYCONST = "MyConstant";

I can't see MYCONST from anywhere even from MyClass, why ?

like image 819
user310291 Avatar asked Nov 27 '22 09:11

user310291


2 Answers

A constant is available in a static context anyway, so remove the static keyword and you'll be fine.

MSDN docs:

The static modifier is not allowed in a constant declaration.

The reason is that a constant's value has to be fully evaluated at compile time and what the compiler does is that it takes that value and replaces all the usages of the constant throughout the code with the constant value.

That is why it sometimes can be better to use a public readonly value instead as the compiler does not replace the usages with the value but instead links to the readonly variable. This is especially something to think about when using constants from another assembly since you might not update all assemblies at once and you might end up with assmblies using the old constant value.

Ref: http://msdn.microsoft.com/en-us/library/e6w8fe1b(v=vs.80).aspx

like image 106
Mikael Östberg Avatar answered Dec 15 '22 00:12

Mikael Östberg


According to the documentation for const

The static modifier is not allowed in a constant declaration.

Remove the static keyword from your constant and it should work.

Edit
Note that a const will be available as a class member, just like when you have static for non const variables. But for const the static is implicit and not allowed to type out.

like image 36
Albin Sunnanbo Avatar answered Dec 15 '22 00:12

Albin Sunnanbo