Tutorial :C# instantiate/initialize object at program startup


I'm a C/C++ programmer recently working in C#, and i'm trying to do some fancy initialization stuff that I've run into some trouble with.

The best and easiest example i can come up with would be that I want to create an "Eager" Singleton - one that is created immediately at program startup, but without me requiring to go into the main function of the program and say "Singleton.Instance()" as the first thing. I read up on static instantiation, and it looks like it has to be called or created before a static object is instantiated, so I tried creating a static variable that instantiate the object, but that did not work. (I couldn't find any documentation on when static variables are instantiated/initialized).

Any pointers?


Edit: after some additional research, I think I can accomplish what I'm looking for with a single block of code utilizing reflection


A static constructor is only called when you first refer to the class that contains the constructor. So when you want your initialization code to run on program startup, you have to explicitly refer to the class containing the constructor in your startup code (the Main method for example).

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »