ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

C# Tutorial• 6 min read

Exception Handling & Resource Disposal (IDisposable)

try-catch-finally, using declarations, and deterministic cleanup

While the garbage collector manages memory, unmanaged resources (database connections, file handles, sockets) must be deterministically released using IDisposable and using.

The using Declaration and Exception Handling

using var stream = File.OpenRead(...);: Automatically calls .Dispose() the microsecond the containing scope exits.

try...catch (Exception ex) when (condition): C# supports exception filters to catch errors only when a boolean condition is satisfied.

Modern using Declaration Pattern
public void ProcessLogs(string path) {
    // using declaration: Disposed automatically at the end of the method!
    using var reader = new StreamReader(path);
    
    string? line;
    while ((line = reader.ReadLine()) != null) {
        if (line.Contains("ERROR")) {
            Console.WriteLine($"Alert: {line}");
        }
    }
} // reader.Dispose() called here deterministically!
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What interface must a C# class implement to be eligible for deterministic resource cleanup via the `using` statement?