Limiting number of objects for a class

I have seen in many interviewers asking about how we can limit the number of objects created for a class. This post explains how to do this in C#. This can be done using a static variable.  Static variable will be invoked before the execution of constructor and it’s value will be destroyed when associated application domain ends.

In this we discuss two methods to limit the class instance to a particular number say 5

Method 1 : Throwing exception from constructor 


class MyClass
{
    public static int Count = 0;
    public MyClass()
    {
        if(MyClass.Count == 5)
            throw new Exception("You can't create more than 5 instances");

else

Count++;

}
}

Well, this class can’t be instantiated more than 5 times.  Some may think that, “what will happen if the exception is handled at the invoking end” ? Exception can be handle, but the object will be of no use when constructor is throwing an exception.

Method 2 : Using a factory method


class MyClass
{
    public static int Count = 0;
    private MyClass()
    {

    }

    public static MyClass GetMyClass()
    {
        if ( MyClass.Count == 5)
            return null;
        else
            return new MyClass();
    }
}

This class uses a factory method GetMyClass() which checks the static variable value and returns an instance of “MyClass”. Since the constructor is private, this class can’t be instantiated directly.

Happy Programming

Advertisements

2 thoughts on “Limiting number of objects for a class

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 )

Google+ photo

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

Connecting to %s