Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are finalisers for?

I have been programming in .NET for four years (mostly C#) and I use IDiposable extensively, but I am yet to find a need for a finaliser. What are finalisers for?

like image 386
open-collar Avatar asked Apr 20 '09 14:04

open-collar


1 Answers

A finalizer is a last ditch attempt to ensure that something is cleaned up correctly, and is usually reserved for objects that wrap unmanaged resources, such as unmanaged handles etc that won't get garbage collected.

It is rare indeed to write a finalizer. Fortunately (and unlike IDisposable), finalizers don't need to be propagated; so if you have a ClassA with a finalizer, and a ClassB which wraps ClassA, then ClassB does not need a finalizer - but quite likely both ClassA and ClassB would implement IDisposable.

For managed code, IDisposable is usually sufficient. Even if you don't clean up correctly, eventually the managed objects will get collected (assuming they are released).

like image 133
Marc Gravell Avatar answered Nov 15 '22 19:11

Marc Gravell