Create default constructor and one static field in class, every time you create object of class the default constructor get called, there you can check how many object already created based on that you can restrictExample : namespace ConsoleApplication1 {class Program{static void Main(string[] args){Employee obj = new Employee();Employee obj1 = new Employee();Employee obj2 = new Employee();Employee obj3 = new Employee();Employee obj4 = new Employee();Employee obj5 = new Employee();Employee obj6 = new Employee();Console.Read();}}class Employee{static int count = 0;public Employee(){if (count == 5){//raise error or deallocate object}else{count++;}}} }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace InheritenceDemo {class Program{static void Main(string[] args){for (int i = 0; i <= 3; i++){Employee emp = new Employee();emp.Print();}Console.ReadLine(); }}class Employee{public static int counter = 0;public Employee(){counter++;if(counter > 3){throw new Exception("Object is trying to get initialized more than 3, which is not allowed.");}Console.WriteLine("Default cons called");}public void Print(){Console.WriteLine("Method called!!");}} }
A simple approach is to have an array of n (3-5), and have a private constructor in your “singleton” class. Then you will have an instanceOf method, which is the only way to get an object. This method will look to see if the number of created objects is < n, if it is, it creates a new one and returns it
@reddy The counter need to be decremented. One can you IDisposable interface to clean the obj state and also to manage instance count. Sample program http://tpcg.io/4k5yXl un-comment line number 12.
By throwing error