How to limit the number of object creation in c# ?


Hi All,

One time i got this question while giving the interview so i m going to write small note on this.

We can limit the number of object creation of class in C# using the static variable.

Static variable is used to share the value to all instance of that class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace LINQ_Test
{
    public partial class Object_Creation : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            MyClass obj = new MyClass();
            MyClass obj1 = new MyClass();
            MyClass obj2 = new MyClass();
            MyClass obj3 = new MyClass();
            MyClass obj4 = new MyClass();
            // MyClass obj5 = new MyClass(); 
            // Exception will throw
        }
    }

    public class MyClass
    {
        public static int Count = 0;
        public MyClass()
        {
            if (MyClass.Count==5)
            {
                throw new Exception("You canot create the object more than 5");
            }
            else
            {
                Count++;
            }
        }
    }
}

Note : In the above sample, we have created the static variable count, which will hold the incremented count value while creating the instance of that class.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.