Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# how to override the Finalize() method?

Tags:

c#

Following function giving compilation error "Do not override object.Finalize. Instead, provide a destructor."

protected override void Finalize()
{           
    this.Dispose();
    base.Finalize();
}
like image 700
Ramakant Badolia Avatar asked May 26 '10 13:05

Ramakant Badolia


People also ask

What does << mean in C?

<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .

What does %d do in C?

%d is a format specifier, used in C Language. Now a format specifier is indicated by a % (percentage symbol) before the letter describing it. In simple words, a format specifier tells us the type of data to store and print. Now, %d represents the signed decimal integer.


1 Answers

The finalizer method is called ~name() replacing "name" with your class name.

The C# compiler will generate the finalizer from this.

But note:

  1. Only use a finaliser if you really need it: your type directly contains a native resource (a type composing a wrapper just uses the Dispose pattern).
  2. Consider specialising SafeHandle rather than writing your own.
  3. Implement the dispose pattern to allow callers to release the resource quickly.
  4. Ensure both your Dispose and Finalizer are idempotent—they can be safely called multiple times.

e.g.

class MyClass : IDisposable {
  private IntPtr SomeNativeResource;

  ~MyClass() {
    Dispose(false);
  }

  public void Dispose() {
    Dispose(true);
  }

  protected virtual void Dispose(bool disposing) {
    if (disposing) {
      // Dispose any disposable fields here
      GC.SuppressFinalize(this);
    }
    ReleaseNativeResource();
  }
}

Subclasses can override Dispose(bool) to add any addition fields they add and call the base implementation.

EDITED: To add example and notes about when to finalise.

like image 168
Richard Avatar answered Oct 12 '22 00:10

Richard