Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: static object variable in class

Tags:

c#

static

If I have a static variable in a class:

public class MyClass {
    private static MyObject = new MyObject();
    public void MyMethod() {
        // do some stuff
    }
}

Can the variable be instantiated when it is declared, as in the above?

like image 478
Craig Johnston Avatar asked Dec 21 '22 19:12

Craig Johnston


2 Answers

Yes. Two particular things to note:

  1. The static variables will be initialized in the order they appear in the class.
  2. They are guaranteed to be initialized before any static constructor is called.

Section 10.5.5.1 of the C# spec goes into more detail in you are interested.

like image 39
Nick Jones Avatar answered Jan 10 '23 00:01

Nick Jones


Your code is legal and works.

One thing to be aware of is that static constructors and initalizers don't run when your module is loaded, but only when needed.
MyObject will only be instantiated when you either create an instance of MyClass or access a static field of it.

10.5.5.1 Static field initialization
The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor (§10.12) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class.

The static constructor for a closed class type executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:
· An instance of the class type is created.
· Any of the static members of the class type are referenced.

So as I understand it:

  • If there is no static constructor the calling of a static method may trigger the initializers but isn't required to do so if the static method uses no static field.
  • If there is a static constructor it must run when a static member is referenced, so calling of a static method triggers first the static field initializers and then the the static constructor.
like image 135
CodesInChaos Avatar answered Jan 10 '23 00:01

CodesInChaos