I am looking at some code and it has this statement:
~ConnectionManager()
{
Dispose(false);
}
The class implements the IDisposable
interface, but I do not know if that is part of that the tilde(~) is used for.
I am looking at some code and it has this statement:
~ConnectionManager()
{
Dispose(false);
}
The class implements the IDisposable
interface, but I do not know if that is part of that the tilde(~) is used for.
~ is the destructor
Finalize
In C#, the Finalize method performs the operations that a standard C++ destructor would do. In C#, you don't name it Finalize -- you use the C++ destructor syntax of placing a tilde ( ~ ) symbol before the name of the class.
Dispose
It is preferable to dispose of objects in a Close()
or Dispose()
method that can be called explicitly by the user of the class. Finalize (destructor) are called by the GC.
The IDisposable interface tells the world that your class holds onto resources that need to be disposed and provides users a way to release them. If you do need to implement a finalizer in your class, your Dispose method should use the GC.SuppressFinalize()
method to ensure that finalization of your instance is suppressed.
What to use?
It is not legal to call a destructor explicitly. Your destructor will be called by the garbage collector. If you do handle precious unmanaged resources (such as file handles) that you want to close and dispose of as quickly as possible, you ought to implement the IDisposable interface.
Finalize
method is called recursively for all instances in the inheritance chain, from the most-derived to the least-derived". Note that that's not the same behaviour you'd get from inheritable destructors, though. –
Aerostation This is a finalizer. To be honest, you should very rarely need to write a finalizer. You really only need to write one if:
IntPtr
) and you can't use SafeHandle
which makes it easierIDisposable
in a class which isn't sealed. (My preference is to seal classes unless they're designed for inheritance.) A finalizer is part of the canonical Dispose pattern in such cases.It is used to indicate the destructor for the class.
try/finally
block that ensures that the parent Finalize
method gets called. Most things that are true of destructors are true of finalizers, and vice versa, but the words mean slightly different things. –
Falgoust Same as C++, it is the destructor; however in C# you do not call it explicitly, it is invoked when the object gets collected by the garbage collector.
See Destructors (C# Programming Guide). Be aware, however that, unlike C++, programmer has no control over when the destructor is called because this is determined by the garbage collector.
~ usually represents a deconstructor. which is run right before a object dies.
© 2022 - 2024 — McMap. All rights reserved.