Azurewrath

Hi all,

In the book I read it says:

"The destructor should only release resources that your object holds on to, and should not reference other objects. Note that if you have only managed references, you don't need to and should not implement a destructor; you want this only for handling unmanaged resources. Because there is some cost to having a destructor, you ought to implement this only on methods that require it (that is, methods that consume valuable unmanaged resources)."

Does this mean, I shouldn't use destructors If so, say I have a static member storing the number of current instances, incremented by the constructor, how do I decrement it when an object is destroyed

Is there any other way around this

Thanks,

aw



Re: Visual C# General Destroying objects

Sergio Arizmendi - exMSFT

You could (I'm thinking of a workaround) implement IDisposable and use the Dispose() method in your objects to decrement the object count.

It's an idea.

Regards :)






Re: Visual C# General Destroying objects

CalvinR

One way is you could create a method called for example release that decrements the counting variable and when it reaches zero it sets the instance of the object to null.

Although I'm assuming your implementing a singleton pattern. If you are trying to keep track of all of the instances of a specific type of object then you wouldn't need to set the instance of the object to null, or you could create an object manager class that handles that for you.





Re: Visual C# General Destroying objects

Azurewrath

Thanks guys. I am not sure how to do that. But I guess that's because of my c# knowledge.

Thanks,

aw





Re: Visual C# General Destroying objects

Robert C. Barth

You don't have any control over when your C# destructor (finalizer) is called anyhow, so it's usefulness is almost nil. Also, the book you read should have said to implement IDisposable, create a Dispose method to get rid of your unmanaged resources.

E.g.:

private bool _disposed = false;

public Dispose()
{
Dispose(true);
GC.SuppresFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
if (_disposed) return;

if (disposing)
// Do clean-up

_disposed = true;
}

You don't really need a finalizer. Additionally, if the clean-up stuff makes calling other methods invalid, use the _disposed member variable to determine if the object has disposed and throw ObjectDisposedException if so.

C# destructors (finalizers) are difficult to write because any reference you have may be invalid in the finalizer since the calls to finalizers is not guaranteed to be in any kind of order. Best to just avoid it and implement the dispose pattern.





Re: Visual C# General Destroying objects

Azurewrath

Thanks Robert. Your example is almost exact to the book. Did you contribute to the book

 

 

Thanks,

aw