Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are const fields converted to static fields at compile time?

Tags:

c#

Why can I call TheFakeStaticClass.FooConst , like it's static, when it's not declared static?

Are const fields converted to static fields at compile time? (I understand that you can't change a const and hence you only need "one instance". I've used many const's before like Math.PI but never thought about before, and now I do and now I am 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;
        }
    }
}
like image 327
radbyx Avatar asked Nov 30 '22 23:11

radbyx


2 Answers

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

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

like image 135
Habib Avatar answered Dec 05 '22 08:12

Habib


Constants are implicitly statics.

The idea of constant is that it must never change and is assigned on compile time. If constants were not statics they would be created at runtime.

like image 21
Leri Avatar answered Dec 05 '22 09:12

Leri