I want to have a Singleton that will be auto instantiated on program start.
What I mean by "auto instantiated" is that the code in the Singleton should instantiate itself on program start without any calls or declarations by other code.
So I want something like the following to instantiate and write out "MySingleton Instantiated" on program start (without the main code doing anything)...
static class MySingleton
{
private static MySingleton self = new MySingleton();
protected MySingleton()
{
System.Console.WriteLine("MySingleton Instantiated");
}
}
except this doesn't work since C# will only initialize the static members of a class when needed, ie when they are accessed/etc.
So what do I do? can this be done?
I haven't done this personally with C++ (haven't been using C++ for a while) but I'm pretty sure it can be done in C++ but not sure about C#.
Any help is appreciated. Thanks.
What I'm actually wanting to do with this is... There would be many of these singleton classes (and more can be added as time goes on), all of which would inherit from a common (abstract) parent class (aka. PClass).
The PClass would have a static member that is a collection of PClasses... and a constructor to add itself to the collection...
Then in theory all the singletons would automagically be added to the collection (since when they are instantiated the base PClass constructor is called and adds the new object to the collection)... then the collection can be used without knowing anything about what child (singleton) classes have been implemented, and new child (singleton) classes can be added any time without having to change any other code.
Unfortunately I can't get the children (singletons) to instantiate themselves... screwing up my little plan, resulting in this post.
Hope I explained that well enough.
PS. Yes I realize there are bad feelings around Singletons and their use... but they are useful sometimes, and even if Satan himself made Singletons I'd still like to know if my problem can be achieved in C#. Thanks kindly to you all.