Wednesday, August 18, 2021

How to restrict object creation to max 3 in .NET?

 This is interview question, which is asked in one of interview.

How you can allow to create only 3 object in C#.NET. It should throw error when user is trying to create more than 3 object.

Here is logic and program.


using System;

using System.Linq;

using System.Collections.Generic;

 namespace ConsoleApp16

{

     public class Student

    {

        static int count = 1;

        public Student()

        {

           if (count <= 3)

            {

                count = count + 1;

            }

            else

            {

                throw new Exception("you cannot create more than 3 instances");

                //count = 0;

            }

          

        }

         public int MyProperty { get; set; }

        public int MyProperty2 { get; set; }

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            Student student = new Student();

            Student student2 = new Student();

            Student student3 = new Student();

            Student student4 = new Student();

           Console.WriteLine("");

        }

    }

}

 

Output:




No comments:

Post a Comment

Write a program to reverse a string? using System; namespace ConsoleApp1 {     class Program     {         static void Main(string[] args)  ...