Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I assume you mean static members of a class? In that case, you can do this:</p> <pre><code>public class MyClass { public static int MyInt = 12; public static MyOtherClass MyOther = new MyOtherClass(); } </code></pre> <p>Those static members are guaranteed to be instantiated before any class is instantiated.</p> <p>If you need complex logic, do it in a static constructor:</p> <pre><code>public class MyClass { public static int MyInt; public static MyOtherClass MyOther; static MyClass() { MyInt = 12; MyOther = new MyOtherClass(); } } </code></pre> <p><strong>Edit</strong></p> <p>Based on your edit, I'd say just assign the values to what they need to be before you instantiate the class, like so:</p> <pre><code>public class MyClass { public static int MyInt; public static MyOtherClass MyOther; } // elsewhere in code, before you instantiate MyClass: MyClass.MyInt = 12; MyClass.MyOther = new MyOtherClass(); MyClass myClass = new MyClass(); </code></pre> <p>That said, this method gives you no guarantee that MyInt and MyOther are set before MyClass is instantiated. It will work, but requires discipline before instantiating MyClass.</p> <p>One alternative pattern you might follow looks like this:</p> <pre><code>public class MyClass { private static int MyInt; private static MyOtherClass MyOther; private static bool IsStaticInitialized = false; public static InitializeStatic(int myInt, MyOtherClass other) { MyInt = myInt; MyOther = other; IsStaticInitialized = true; } public MyClass() { if(!IsStaticInitialized) { throw new InvalidOperationException("Static Not Initialized"); } // other constructor logic here. } } // elsewhere in your code: MyClass.InitializeStatic(12, new MyOtherClass()); MyClass myClass = new MyClass(); // alternatiavely: MyClass myClass = new MyClass(); // runtime exception. </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload