This is a destructor. The syntax is inherited from C++. But the semantics are quite different.
In practice destructors do not exist in language. To understand I will explain two other concepts.
Dispose()
This is a method available in all types that implement the interface IDisposable
and allows resources to be released when the object is no longer needed. The Dispose()
can be done manually at any time or automatically using the statement using
. The release of resources are free memory. Only the Garbage Collector allows to free up memory. If a type does not need to have external resources, it is unnecessary.
Finish
This is the method that actually processes everything that is necessary in the moment before the release of memory. We can say that he is responsible for liberation, although actually who does this is the Garbage Collector. A finalize()
is always available, because he is part of the type Object
and in most cases the standard implementation of Object
is enough.
Destructor
You can’t override a method Finalize()
on its type. The compiler does not allow you to use your own implementation. But it allows the destructor to be created. And he can process what he wants in the destructor and call the Finalize()
. The standard implementation of Finalize
needs to be available in all types.
So the code
class Car {
~Car() { // destrutor
// código de limpeza...
}
}
is the same as
protected override void Finalize() {
try {
// código de limpeza...
} finally {
base.Finalize();
}
}
but the second way can only be generated by the compiler in place of the destructor.
Therefore a destructor in C# is neither executed soon after the object is no longer needed, nor is it executed in the same thread and yes in the thread of Garbage Collector. There are a number of problems related to the finalizing method that are not part of the question’s scope. Finishers, even if in destructor form should only be customized when the programmer deeply understands all its implications.
I put in the Github for future reference.
A little outside the main scope of the question, but it may be of interest to you to know, the operator
yield
shall be understood as an operator of accumulation. For example:public IEnumerable<int> ListaDeNumeros() { for (int i = 1; i <= 100; i++) { yield return i; } }
The code will make 100 Returns, accumulating the result in a kind of aList<int>
with numbers from 1 to 100.– Leonel Sanches da Silva
@Ciganomorrisonmendez Yes, Yield I met a little while ago and I find very interesting the use of it, as I said is that really since the first time I started programming 4 years ago, I believe today must have been the first time I saw the destructor in C# rsrs..
– Tafarel Chicotti