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