Alex Rivera | Logout

When should I create a destructor?

Asked 2011-02-04T13:55:31.430
210

For example:

public class Person
{
    public Person()
    {
    }

    ~Person()
    {
    }
}

When should I manually create a destructor? When have you needed to create a destructor?

Edit
Report

2 Answers

17

It's called a "finalizer", and you should usually only create one for a class whose state (i.e.: fields) include unmanaged resources (i.e.: pointers to handles retrieved via p/invoke calls). However, in .NET 2.0 and later, there's actually a better way to deal with clean-up of unmanaged resources: SafeHandle. Given this, you should pretty much never need to write a finalizer again.

answered 2011-02-04T14:01:22.577
4

When you have unmanaged resources and you need to make sure they will be cleaned up when your object goes away. Good example would be COM objects or File Handlers.

answered 2011-02-04T13:59:48.473

Your Answer