Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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?

like image 662
Master Morality Avatar asked Jun 11 '11 15:06

Master Morality


People also ask

When and how obtain a static constructor called?

A static constructor is called automatically. It initializes the class before the first instance is created or any static members declared in that class (not its base classes) are referenced. A static constructor runs before an instance constructor.

Can static constructor can access non-static?

yes we can have static constructor inside a non-static class. Yes, it can. But user will not have any control on its invoke.

Can constructor access static members?

You can define a static field using the static keyword. If you declare a static variable in a class, if you haven't initialized it, just like with instance variables compiler initializes these with default values in the default constructor. Yes, you can also initialize these values using the constructor.

Why static constructor has no access modifier?

Because you can't call a static constructor directly, you can't include an access modifier (e.g. public, private) when defining a static constructor. Static constructors are defined without access modifiers.


1 Answers

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!

like image 99
Ben Voigt Avatar answered Oct 26 '22 08:10

Ben Voigt