Click here to Skip to main content
15,907,687 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
My Application has one class and i want to apply the restriction for objects creation. It can instantiate only three time in application.
Posted

C#
private const int max = 3;
private static int counter = 0;
private static readonly object m_lock = new object();

public static MyClass CreateInstance()
{
    lock (m_lock)
    {
        return (++counter > max) ? null : new MyClass();
    }
}

private MyClass()
{

}



RS Note: Added lock for thread safety.
 
Share this answer
 
v4
You may use the Singleton design pattern.
:)
 
Share this answer
 
C#
public class classname
{
   private static classname instance;
   private Singleton() {}
   public static classname Instance
   {
      get 
      {
         if (instance <= 3)
         {
            instance = new classname();
         }
         return instance;
      }
   }
}


Singleton creates single instance,

I am not sure about this but, this may help....
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900