Need destructors in C #?

I have a concern. I am a first year student of computer science. Usually I am very curious in the class, but not always my teacher has an answer or does not always know the answer. Are destructors necessary in C #? I mean, if I need to implement a destructor method, as I usually do with constructors, is this a good practice, or can I avoid it and the garbage collector will do this for me?

+4
source share
3 answers

Destructors (or finalizers) are good for the language - but you will almost never use them. Basically you only need them if you have a direct pen on an unmanaged resource, and this is not only incredibly rare, but SafeHandleas a tiny level of indirection, this is in any case the best idea (which handles cleaning for you). See the Joe Duffy related blog for more information .

For what it's worth, I can't remember the last time I wrote the finalizer, except to test for some odd behavior or something else.

For most of the time, life is easier:

  • Garbage collector can handle memory cleanup
  • (, ) , using, , , .
  • ( - , IDisposable) , IDisposable. ( , . , , sealed, , , , .)
+12

# . , # , , . , , , , , , ++.

+3

. .

, . ( , )

GC , . .

, IDisposable .

+2

Source: https://habr.com/ru/post/1536209/


All Articles