IDisposable and Using
Release resources deterministically with using declarations.
Introduction
Managed memory is reclaimed automatically, but files, sockets, and similar resources should be disposed promptly.
The using declaration guarantees Dispose runs at the end of the scope, including when an exception occurs.
Runnable C# example
Program.cs
using System;
using System.IO;
class Program
{
static void Main()
{
using var writer = new StringWriter();
writer.Write("resource-safe output");
Console.WriteLine(writer.ToString());
}
}
resource-safe outputPractice with the debugger
Set a breakpoint on an important assignment or condition, click Debug, and inspect the local values before stepping to the next line.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges