Constructors and Finalizers

suggest change

Constructors are methods in a class that are invoked when an instance of that class is created. Their main responsibility is to leave the new object in a useful and consistent state.

Destructors/finalizers are methods in a class that are invoked when an instance of that is destroyed. In C# they are rarely explicitly written/used.

C# does not actually have destructors, but rather finalizers which use C++ style destructor syntax. Specifying a destructor overrides the Object.Finalize() method which cannot be called directly.

Unlike other languages with similar syntax, these methods are not called when objects go out of scope, but are called when the Garbage Collector runs, which occurs under certain conditions. As such, they are not guaranteed to run in any particular order.

Finalizers should be responsible for cleaning up unmanaged resources only (pointers acquired via the Marshal class, received through p/Invoke (system calls) or raw pointers used within unsafe blocks). To clean up managed resources, please review IDisposable, the Dispose pattern and the using statement.

(Further reading: When should I create a destructor?)

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents