I’m currently working on a project and I’m a bit stumped. In C++, in order to make sure some objects were created before Main (), I would create a static instance at the bottom of the .cpp file, say for example:
class MyClass {
public:
MyClass () { someVariable = "HelloWorld"; }
~MyClass () {}
void someFunction () { cout << someVariable << endl; }
private:
string someVariable;
};
static MyClass myClass;
I was wondering is it possible to do the same thing in C#? I’ve been trying to declare my instances everywhere to get it to work but no luck so far, so any help is very much appreciated!
The
Mainmethod is in a static class (as every method has to be in a class in C#), so you can add a static constructor to that class.The static constructor is guaranteed in the specification to run before any of the static members in the class is used, so it will run before the static member
Mainis called.