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?
Yes. Two particular things to note:
Section 10.5.5.1 of the C# spec goes into more detail in you are interested.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With