Chris
Chris

Reputation: 4485

C# class: Do logging / housekeeping, should I use a destructor?

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):

Upvotes: 2

Views: 2481

Answers (3)

Kyle W
Kyle W

Reputation: 3752

If you want something to run when it's done, you should implement IDisposable.

Upvotes: 0

user195488
user195488

Reputation:

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:

In general, C# does not require as much memory management as is needed when you develop with a language that does not target a runtime with garbage collection. This is because the .NET Framework garbage collector implicitly manages the allocation and release of memory for your objects. However, when your application encapsulates unmanaged resources such as windows, files, and network connections, you should use destructors to free those resources. When the object is eligible for destruction, the garbage collector runs the Finalize method of the object.

and finally on performance:

When a class contains a destructor, an entry is created in the Finalize queue. When the destructor is called, the garbage collector is invoked to process the queue. If the destructor is empty, this just causes a needless loss of performance.

There are other ways to manage resources besides a destructor:

Cleaning Up Unmanaged Resources

Implementing a Dispose Method

using Statement (C# Reference)

Upvotes: 2

Henk Holterman
Henk Holterman

Reputation: 273169

No that would not be the best way, a destructor is costly.

The best way would be to add a Close() or maybe the Dispose() (IDiposable interface) method.

But you need to define very carefully what "not in use anymore" means, and if you want the extra trouble to manage and track that.

You can use a destructor to automate it, but it would be better to make that conditional (Debug config only). Also consider that the destuctor implements "non deterministic" finalization.

Upvotes: 2

Related Questions