IDisposable and Using
Managed memory is reclaimed automatically, but files, sockets, and similar resources should be disposed promptly.
How it works
Release resources deterministically with using declarations.
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.