are destructors necessary in C#?

I have a concern. I'm a first year student of computer science. Normally I'm very inquisitive in class but, not always my teacher has an answer, or not always knows the answer. Are destructors necessary in C#? What I mean is if I have to implement a destructor method as I normally do with constructors, is it a good practice or i can avoid it and the garbage collector will do it for me?

Jon Skeet
people
quotationmark

Destructors (or finalizers) are good to have in the language - but you should almost never use them. Basically you should only need them if you have a direct handle on an unmanaged resource, and not only is that incredibly rare, but using SafeHandle as a tiny level of indirection is a better idea anyway (which handles clean-up for you). See Joe Duffy's blog post on the topic for more details.

For what it's worth, I can't remember the last time I wrote a finalizer other than to test some odd behaviour or other.

For the vast majority of the time, life is simpler:

  • The garbage collector can handle memory resource cleanup
  • If you use an unmanaged resource (e.g. a file) locally within a method, use a using statement to make sure you release it when you're done with it
  • If you need a reference to an unmanaged resource (or anything else which implements IDisposable) as an instance variable within your type, your type should itself implement IDisposable. (I try to avoid this where possible. Even when it is necessary, you can make life simpler by making your class sealed, at which point you at least don't need to worry about other subclasses having even more unmanaged state to clean up.)

people

See more on this question at Stackoverflow