Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 198357
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T16:55:50+00:00 2026-05-11T16:55:50+00:00

I want to have a Singleton that will be auto instantiated on program start.

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T16:55:50+00:00Added an answer on May 11, 2026 at 4:55 pm

    The IoC approach mentioned by Chris is probably the best, but failing that the “best” solution I can think of is to do something funky with reflection and attributes along the lines of:

    public class InitOnLoad : Attribute 
    { 
        public static void Initialise()
        {
            // get a list of types which are marked with the InitOnLoad attribute
            var types = 
                from t in AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes())
                where t.GetCustomAttributes(typeof(InitOnLoad), false).Count() > 0
                select t;
    
            // process each type to force initialise it
            foreach (var type in types)
            {
                // try to find a static field which is of the same type as the declaring class
                var field = type.GetFields(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).Where(f => f.FieldType == type).FirstOrDefault();
                // evaluate the static field if found
                if (field != null) field.GetValue(null);
            }
        }
    }
    
    [InitOnLoad]
    public class Foo
    {
        public static Foo x = new Foo();
    
        private Foo()
        {
            Console.WriteLine("Foo is automatically initialised");
        }
    }
    
    public class Bar
    {
        public static Bar x = new Bar();
    
        private Bar()
        {
            Console.WriteLine("Bar is only initialised as required");
        }
    }
    

    With a call to InitOnLoad.Initialise() added to your main method.

    You could do away with the attribute, but this may cause unnecessary types to be initialized and needlessly consume memory (such as Bar in the above code).

    It’s also worth noting that this won’t handle types contained in any assemblies which are loaded dynamically, unless you make another call to Initialise, but based on your question (“auto instantiated on program start”) that doesn’t sound like an issue for you.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 103k
  • Answers 103k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Stackoverflow.com uses reCAPTCHA. And, I too have noticed that when… May 11, 2026 at 8:26 pm
  • Editorial Team
    Editorial Team added an answer Study the KVO Programming Guide, Registering Dependent Keys. You can't… May 11, 2026 at 8:26 pm
  • Editorial Team
    Editorial Team added an answer Generally I avoid putting blobs in the database if there… May 11, 2026 at 8:26 pm

Related Questions

I have a program that will analyzes source code. It can recursively go through
I have a very bad feeling about using lock in my code but now
I'm aiming to create a set of objects, each of which has a unique
I am developing a Java web application that bases it behavior through large XML
As an exercise, I'm translating parts of our large and battle-hardened Delphi-framework to C#.

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.