Are const fields converted to static fields at compile time?

Why can I call TheFakeStaticClass.FooConst as static when it is not declared static?

Are constant fields converted to static fields at compile time? (I understand that you cannot change const and therefore you only need β€œone instance.” I used a lot of constants earlier than Math.PI , but I never thought about it before, and now I do it, and now I curious.

 namespace ConstTest { class Program { class TheFakeStaticClass { public const string FooConst = "IAmAConst"; } class TheRealStaticClass { public static string FooStatic = "IAmStatic"; } static void Main() { var fc = TheFakeStaticClass.FooConst; // No error at compile time! var fs = TheRealStaticClass.FooStatic; var p = new Program(); p.TestInANoneStaticMethod(); } private void TestInANoneStaticMethod() { var fc = TheFakeStaticClass.FooConst; var fs = TheRealStaticClass.FooStatic; } } } 
+4
source share
4 answers

From Jon Skeet - Why can't I use static and const together

All constant declarations are implicitly static , and the C # specification states that the (redundant) inclusion of a static modifier is prohibited.

+10
source

Constants are implicitly static.

The idea of ​​a constant is that it should never change and is assigned at compile time. If the constants were not static, they would be created at runtime.

+5
source

const, as you say, is also static. The difference begins with the fact that const cannot be changed.

+2
source

No. They are built in. This means that every time the compiler sees the use of a constant, it replaces the use with a constant value. This is why consts need to be evaluated at compile time.

+2
source

All Articles