I have a c# class. Whenever this class is not in use anymore I want to do some things. For example log the current state and so on.
I want to be sure that this method is run everytime when the class is not used anymore.
I don’t want just use a simple method because I can’t be sure that every user is calling it.
I have no resources (like file handles) to clear up.
Is the best way to use a destructor?
“not in use” is when (for example):
- a user uses my class in a form and the form is closed
- the class is used in an application and this application is shut down
It depends. C# .NET utilizes a garbage collector that implicitly cleans up objects for you. Normally, you cannot control the clean up of objects – the garbage collector does that. You can implement a destructor in your class if you desire, but you may get a performance hit. MSDN has this to say on destructors:
and finally on performance:
There are other ways to manage resources besides a destructor:
Cleaning Up Unmanaged Resources
Implementing a Dispose Method
using Statement (C# Reference)