Why can't I access public const in C #?

I have something like this:

namespace MyNamespace { public partial class MyClass: UserControl { public static const String MYCONST = "MyConstant"; 

I canโ€™t see MYCONST anywhere even from MyClass, why?

+4
source share
5 answers

In any case, the constant is available in a static context, so remove the static and everything will be fine.

MSDN docs:

A static modifier is not allowed in a constant declaration.

The reason is that the constant value must be fully evaluated at compile time, and what the compiler does is that it takes this value and replaces all uses of the constant in the whole code with a constant value.

Therefore, it is sometimes better to use the readonly public value instead of the compiler not replacing custom with a value, but instead referring to the readonly variable. This is especially important when using constants from another assembly, since you can not update all assemblies at once, and you can get assmblies using the old constant value.

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

+11
source

According to the documentation for const

A static modifier is not allowed in a constant declaration.

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

Edit
Note that const will be available as a member of the class, just as when you have static for const variables. But for const static implicit and not allowed to print.

+6
source

What type of compiler are you using?

In general, posting constants is not a good idea. They behave differently than readonly variables; their literal value is compiled into IL. This is a problem if the constant is declared in another assembly. You could, say, send a bug fix for an assembly that changed the value of const. However, other assemblies in your product will continue to use the old value. Jitter will not complain about the mismatch. Not good.

A public const is fine if it is a "manifest" constant. Like Math.PI, only running code in a different universe can produce unexpected results. The name of the product or company is already quite risky.

+5
source

It should be available as MyNamespace.MyClass.MYCONST

+3
source

There is a compilation error in the code.

When I compile my code, I get the following:

The constant 'MyNamespace.MyClass.MYCONST' cannot be marked as static

See the motivation for this error on Eric Lippert's blog:

+2
source

Source: https://habr.com/ru/post/1344194/


All Articles