In C#, is there a way to stop instantiating class, say after 'n' instantiations ? This link doesn't help much.
About trying out things, I was thinking of making the class static, but 'n' instantiations have to achieved before stopping the instantiations. Is it possible through Reflection ?
You may have a private static counter, increment it in the constructor and throw an Exception if your limit is reached. But notice, this is a very strange and most probably bad design. A better way would be a factory pattern
class LimitedInstantiation
{
private static int instCounter = 0;
public LimitedInstantiation()
{
instCounter++;
// limit your number of instances
if (instCounter > 3)
{
throw new Exception("Limit of instances reached");
}
}
~LimitedInstantiation()
{
// Reduce your number of instances in the destructor
instCounter--;
}
}
You can test if like this:
try
{
var instance1 = new LimitedInstantiation();
var instance2 = new LimitedInstantiation();
var instance3 = new LimitedInstantiation();
// this should fail.
var instance4 = new LimitedInstantiation();
}
catch (Exception e)
{
Console.WriteLine(e);
}