C #: static object variable in class

If I have a static variable in the class:

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

Is it possible to instantiate a variable when it is declared, as described above?

+4
source share
3 answers

Your code is legal and works.

One thing to know about is that static constructors and initializers do not start when your module loads, but only if necessary.
MyObject will only be created when you instantiate MyClass or access its static field.

10.5.5.1 Initialization of a static field
The initializers of a static variable of a class field 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 exists in the class (ยง 10.12), the execution of the initializers of the static field occurs immediately before the execution of this static constructor. Otherwise, the static field initializers are executed at the implementation-dependent time until the first use of the static field of this class.

A static constructor for a closed class type is executed no more than once in a given application domain. The execution of the static constructor is triggered by the first of the following events in the application domain:
ยท An instance of the class type has been created.
ยท A reference to any of the static members of the class type.

So, I understand:

  • If there is no static constructor, calling a static method can initiate initializers, but you do not need to do this if the static method does not use a static field.
  • If a static constructor exists, it must be started when the static member is referenced, so calling the static method first starts the static field initializers, and then the static constructor.
+6
source

Yes. Two features should be noted:

  • Static variables will be initialized in the order in which they appear in the class.
  • They are guaranteed to be initialized before any static constructor is called.

Section 10.5.5.1 of C # spec interests you in more detail.

+4
source

If you ask if this is legal C #, then yes it is. And he will do what you think will be.

+1
source

Source: https://habr.com/ru/post/1333279/


All Articles