Hi,
Please check the following code,
Code Block
class MyClass
{
public static int Count = 0;
public MyClass()
{
if(count == 5)
//I need to destroy this instance
else
count++
}
}
Visual C# Language
class MyClass
{
public static int Count = 0;
public MyClass()
{
if(count == 5)
//I need to destroy this instance
else
count++
}
}
Hi,
Just try this code
class
MyClass{
public static int Count = 5;
public MyClass()
{
if(Count == 5)
throw new Exception("Can't create more than five objects"); else
Count++;
}
}
Regards,
Manju Sandhu
Hi,
You can do this like this, by creating a factory method and having private constructor.
LIke this
class
MyClass{
public static int Count = 0;
private MyClass()
{
Count++;
}
public static MyClass Factory()
{
if (Count==5)
return null;
else
return new MyClass();
}
}
And use this like this
MyClass obj = MyClass.Factory();
I hope this solve your problem.
Regards,
Manju Sandhu
Navaneeth wrote:
Thanks but, it's foolishness to do so. Because I can catch that exception where I am invoking the class and I can continue using the object. Throwing an exception won't make the class instance not usable.
No you can't continue using the object, because you will not have a reference to it if the constructor throws, even if you cantch the exception.