简体   繁体   中英

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?

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 (eg 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.)

No destructors are not neccesary in C#. The reason why that's true is that in C# the memory is managed automatically and you haven't to do anything except from creating an object. When the garbage collector verifies that an object is not referred anywhere else in your application, then it reclaims its memory, without having you declared any destructor for this object, like we do on C++ for instance.

Nothing is unnecessary in any language. They serve their purpose.

Destructors will destruct the object and you'll end up with object resurrection.( If you try to access destructed object, you might get an error )

GC will automatically do this for you when the object has no longer any references to it. So there's is no need for you to do this explicitly..

Also, implementing IDisposable should be given preference over destructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM