Search code examples
c#staticstatic-constructor

.Net : Do static constructors get called when a constant is access?


So here is what I'm thinking...

public class MyClass
{
    public const string MyConstant = "MyConstantValue";

    private static MyClass DefaultInstance;

    static MyClass()
    {
         DefaultInstance = new MyClass();
    }
}

...

NotificationService.RegisterForNotification(MyClass.MyConstant, Callback);

Will this work or do I need to use something like a static readonly property field to trigger the static constructor?


Solution

  • Use of a constant doesn't necessarily result in a member access which would cause the static constructor to be called. The compiler is allowed to (encouraged, even) substitute the value of the constant at compile time.

    Your suggested workaround of static readonly should be ok, although readonly suggests a field, not a property. Properties are read-only when they have no setter, the readonly keyword isn't involved.

    A simple example:

    class HasSConstructor
    {
        internal const int Answer = 42;
        static HasSConstructor()
        {
            System.Console.WriteLine("static constructor running");
        }
    }
    
    public class Program
    {
        public static void Main()
        {
            System.Console.WriteLine("The answer is " + HasSConstructor.Answer.ToString());
        }
    }
    

    Output under .NET 4.0:

    The answer is 42

    The static constructor never runs!