Navaneeth


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++

}

}



I tried to distroy like this = null. But it throws error like this is readonly. How can I do this. I want to restrict the class instances to 5. If count goes more than 5, the object has to be destroyed. Anyway to do so




Re: Clearing class instance

Manju Sandhu


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





Re: Clearing class instance

Navaneeth

Hi Manju,

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.






Re: Clearing class instance

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





Re: Clearing class instance

Mattias Sjogren

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.






Re: Clearing class instance

Navaneeth

Hi,

Great Manju and Mattias. Both worked. Thanks