C # has finalizers, such as C ++, that are called when an object is destroyed. They are in the same form as C ++, namely:
~ClassName() { }
As you know, C # does not have deterministic memory management, and therefore this is not a very big guarantee. As a direct result, you should not use finalizers to free unmanaged resources in C #. Instead, we use the IDisposable interface. This provides the only method for the Dispose developer to call when you want to free unmanaged resources.
public class MyDisposable : IDisposable { public void Dispose() {
We can also use using sugars to allow the semantic call of Dispose() when the using block completes (elegantly or not).
using(var disposable = new MyDisposable) {
If you find that you are using finalizers and Dispose , you can use the GC.SuppressFinalize method, although this is a bit out of my scope. StackOverflow had a really good discussion about it here
This can be used to fool RAII-esque, for example,
using(var guard = new Guard(resource)) { }
source share