Komara Reddy
Ho can you restrict to creating only 3 objects for a class at any time ?
By Komara Reddy in OOP/OOD on Oct 17 2016
  • Komara Reddy
    Oct, 2016 17

    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++;}}} }

    • 5
  • Sunil Gupta
    Jun, 2019 26

    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!!");}} }

    • 1
  • Roshan Rathod
    Jul, 2020 19

    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

    • 0
  • N Raj
    Apr, 2018 15

    @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.

    • 0
  • Mukesh Kumar
    Sep, 2017 22

    By throwing error

    • 0

Most Popular Job Functions


MOST LIKED QUESTIONS