Search⌘ K

Automatic Disposing

Explore how to simplify resource management in C# by using the using construct, which ensures automatic calling of Dispose() on objects implementing IDisposable. Understand why this approach improves code readability and robustness over manual try...finally blocks, and learn about scope advancements in C# 8.0 that extend using for cleaner disposal.

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 ...