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;
}
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With