Automatic Disposing

Learn to work with types that implement the IDisposable interface.

Introduction

It’s important to call the Dispose() method in a robust manner by putting everything inside a try...finally block.

Course course = null;
try
{
	course = new Course() { Title = ".NET Fundamentals" };
}
finally
{
	course?.Dispose();
}

However, if we have many objects in our program that use unmanaged resources, our code is filled with try...finally blocks. There must be a better approach.

The using construct

C# syntax allows us to replace the try...finally blocks used with objects that implement the IDisposable interface to make our code more concise. When working with such objects, we can use the using construct:

using(var course = new Course() { ".NET Fundamentals" })
{
	// Use the object
} // Dispose() called automatically when this ending curly brace is reached

The using construct wraps a block of code that creates an object of some type that implements the IDisposable interface. The object’s Dispose() method is called automatically when the code block is completed.

Note: We can’t use the using block with any arbitrary object. It must implement the IDisposable interface.

Let’s test an example to confirm that the using block executes the Dispose() method at the end:

Get hands-on with 1200+ tech skills courses.