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

C# Concepts Posted May 14, 2021

You can now show your support. 😊

We use cookies to provide you with a great user experience, analyze traffic and serve targeted promotions.   Learn More   Accept