How can you restrict the number of instances that can be created on a class?

  • To keep a track on the number of instances created on a class, you can maintain a static counter that is incremented each time the constructor is called. By principle, the constructor is called exactly once whenever a new instance is created.
  • If the counter reaches over a limit, you can throw an Exception which breaks the instantiation.
    class MyClass2
    {
        private static int _counter = 0;
        public MyClass2()
        {
            if (_counter > 2)
            {
                throw new Exception("Instances created beyond limit");
            }
            else
            {
                ++_counter;
            }
        }

        public void ShowCounter()
        {
            Console.WriteLine($"Counter is at {_counter}");
        }
    }
    
    
    MyClass2 c;
    for (int i = 0; i < 5; i++)
    {
        c = new MyClass2();
        c.ShowCounter();
    }
    
    output:
    Counter is at 1
    Counter is at 2
    Counter is at 3
    Unhandled exception. System.Exception: Instances created beyond limit
  • To keep a track on the number of instances created on a class, you can maintain a static counter that is incremented each time the constructor is called. By principle, the constructor is called exactly once whenever a new instance is created.
  • If the counter reaches over a limit, you can throw an Exception which breaks the instantiation.
    class MyClass2
    {
        private static int _counter = 0;
        public MyClass2()
        {
            if (_counter > 2)
            {
                throw new Exception("Instances created beyond limit");
            }
            else
            {
                ++_counter;
            }
        }

        public void ShowCounter()
        {
            Console.WriteLine($"Counter is at {_counter}");
        }
    }
    
    
    MyClass2 c;
    for (int i = 0; i < 5; i++)
    {
        c = new MyClass2();
        c.ShowCounter();
    }
    
    output:
    Counter is at 1
    Counter is at 2
    Counter is at 3
    Unhandled exception. System.Exception: Instances created beyond limit

Buy Me A Coffee

Found this article helpful? Please consider supporting!

Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *