Interviews - C# Corner

Komara Reddy
Ho can you restrict to creating only 3 objects for a class at any time ?
By Komara Reddy in OOP/OOD onOct 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
  • 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 Companies

Most Popular Job Functions

MOST LIKED QUESTIONS