Modern .NET APIs · 8 min read · Beginner
Exceptions & IDisposable (using)
Handle failures cleanly with try/catch/finally and automatically release resources with C#'s using declaration.
What you'll learn
- Use using var resource = ... to guarantee Dispose() runs at scope exit
- Catch specific exceptions and preserve stack traces with bare throw;
- Implement IDisposable on custom resource wrappers
In C#, any type that holds unmanaged resources (files, DB connections, HTTP clients) implements IDisposable. Prefixing the variable with using var guarantees Dispose() is called automatically at the end of the enclosing scope, even if an exception occurs.
Fill-in-the-Blank Exercise
Auto-Disposing Resource
Ensure reader.Dispose() runs automatically when the scope ends.
var reader = new StringReader("C# 12");
Console.WriteLine(reader.ReadLine());Live Code Lab
C#UsingDemo.cs
Expected OutputClick “Run Live” to compile with Mono C#
Read: Line 1 Caught FormatException: The input string 'not-a-number' was not in a correct format
Check Your Understanding
Score: 0 / 1
1. What does using var conn = new SqlConnection(...); guarantee in C#?
Study Workspace
Finished this lesson?
Your progress is saved locally in your browser, no account needed.