views:

774

answers:

3

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?

Thanks!

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

+2  A: 

See Jon Skeet's Article on implementing singletons in C# - http://www.yoda.arachsys.com/csharp/singleton.html

AB Kolan
thanks, that was the first place I looked, but it unfortunately doesn't answer my question about how(if it's possible) to create a truley eager singleton/class/static, only a "less lazy" one. As mentioned, I'm looking for this static object to be instantiates and initialized on run, without having to manually create it or call it's method. I may not be able to with a high language like this, but that's why ok asking :)
cyberconte
A: 

here's a good summary

maybe you are building the instance in the getter of a static property ... maybe try to instanciate the singleton in the static ctor!

Andreas Niedermair
+2  A: 

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).

Ronald Wildenberg