Why this post exists
This is Part 2 of Day 4 in my six-day C# deep dive. Part 1 covered extension methods, pattern matching and records. This post covers the tools that make real programs reliable: cleaning up resources with IDisposable, JSON, unit testing, and dependency injection.
Each concept has what it is, an analogy, a short example, a practice question and a complete solution with the reasons it is written that way. Concepts 10 to 13 continue the numbering from Part 1. Try each practice question yourself before reading the solution.
All code targets .NET 8 or later. Most examples use top-level statements, so you can paste them into the Program.cs of a new console project. The testing section uses a small library project plus a test project, and each file is labelled.
Concept 10: IDisposable, using and resource cleanup
What it is. Memory is cleaned up automatically by the garbage collector, but some resources are not just memory: file handles, database connections, network sockets. They are limited, they can stay locked, and the garbage collector decides when to clean up, which could be seconds or minutes later. A class that holds such a resource implements IDisposable, and callers release it deterministically with a using statement.
The analogy: a hotel key card. The garbage collector is a cleaner who tidies the rooms at unpredictable times. If you leave the hotel without returning your key, the room stays unavailable to other guests until the cleaner eventually notices. Dispose is handing back the key at the front desk the moment you leave. using is the checkout slot that does it for you, even if you leave in a hurry because something went wrong.
using (var a = new Tracer("A")) // using block: Dispose runs at the closing brace { Console.WriteLine("working in A"); } using var b = new Tracer("B"); // using declaration: Dispose runs at the end of the scope Console.WriteLine("working in B (it stays open until the program ends)"); try { using var c = new Tracer("C"); throw new InvalidOperationException("boom"); // C is still disposed on the way out } catch (InvalidOperationException ex) { Console.WriteLine($"caught: {ex.Message}"); } Console.WriteLine("end of the program"); class Tracer : IDisposable { private readonly string _name; public Tracer(string name) { _name = name; Console.WriteLine($" open {_name}"); } public void Dispose() => Console.WriteLine($" close {_name}"); } Output:
open A working in A close A open B working in B (it stays open until the program ends) open C close C caught: boom end of the program close B What is happening here:
- A
usingblock disposes the object at the closing brace. A using declaration (using var b = ...) disposes it at the end of the enclosing scope, with less nesting. -
usingis shorthand fortry { ... } finally { x.Dispose(); }, which is whyCwas still closed after the exception. - Multiple resources dispose in reverse order of creation, like unwinding a stack.
- For asynchronous cleanup, implement
IAsyncDisposableand useawait using. - Disposing is separate from the object's memory. After
Disposethe object still exists, but it should refuse to be used.
Practice question 10: wrap a file in a correct dispose pattern
Wrap a file (or a connection) in a class that implements the dispose pattern correctly.
Solution
string path = Path.Combine(Path.GetTempPath(), "day4-logfile.txt"); Console.WriteLine("-- the file is flushed and closed when the block ends --"); using (var log = new LogFile(path)) { log.Write("first"); log.Write("second"); } Console.WriteLine($"lines on disk: {File.ReadAllLines(path).Length}"); Console.WriteLine("-- use after dispose --"); var closed = new LogFile(path); closed.Dispose(); try { closed.Write("too late"); } catch (ObjectDisposedException ex) { Console.WriteLine($"ObjectDisposedException for {ex.ObjectName}"); } Console.WriteLine("-- dispose twice --"); closed.Dispose(); Console.WriteLine("no error"); Console.WriteLine("-- nested usings dispose in reverse order --"); using (var outer = new Connection("outer")) using (var inner = new Connection("inner")) { Console.WriteLine(" working"); } Console.WriteLine("-- an exception still disposes --"); try { using var risky = new Connection("risky"); throw new InvalidOperationException("boom"); } catch (InvalidOperationException ex) { Console.WriteLine($" caught: {ex.Message}"); } Console.WriteLine("-- the full pattern, for a class others will inherit from --"); using (var audited = new AuditedFile(path)) { audited.Write("hello"); } // Recommended default: a sealed class that owns only managed resources public sealed class LogFile : IDisposable { private readonly StreamWriter _writer; private bool _disposed; public LogFile(string path) => _writer = new StreamWriter(path); public void Write(string message) { ObjectDisposedException.ThrowIf(_disposed, this); _writer.WriteLine(message); } public void Dispose() { if (_disposed) return; // safe to call more than once _disposed = true; _writer.Dispose(); } } public sealed class Connection : IDisposable { private readonly string _name; public Connection(string name) { _name = name; Console.WriteLine($" open {_name}"); } public void Dispose() => Console.WriteLine($" close {_name}"); } // The full pattern: only needed when the class is NOT sealed (or holds an unmanaged resource directly) public class ManagedFile : IDisposable { private StreamWriter? _writer; private bool _disposed; public ManagedFile(string path) => _writer = new StreamWriter(path, append: true); public void Write(string message) { ObjectDisposedException.ThrowIf(_disposed, this); _writer!.WriteLine(message); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); // no finalizer needed now, but a subclass may add one } protected virtual void Dispose(bool disposing) { if (_disposed) return; if (disposing) { _writer?.Dispose(); // managed resources are released only on the explicit path _writer = null; } _disposed = true; } } public class AuditedFile : ManagedFile { public AuditedFile(string path) : base(path) { } protected override void Dispose(bool disposing) { if (disposing) Console.WriteLine(" AuditedFile cleaning up"); base.Dispose(disposing); // always call the base so its resources are released } } Output:
-- the file is flushed and closed when the block ends -- lines on disk: 2 -- use after dispose -- ObjectDisposedException for LogFile -- dispose twice -- no error -- nested usings dispose in reverse order -- open outer open inner working close inner close outer -- an exception still disposes -- open risky close risky caught: boom -- the full pattern, for a class others will inherit from -- AuditedFile cleaning up Why this is the best way to write it:
-
LogFileis the recommended default:sealed, with a simpleDispose. If a class owns only managed resources (like aStreamWriter) and nobody can inherit from it, the one-method version is all you need. No finalizer, noDispose(bool). -
Disposeis safe to call twice. The_disposedflag makes the second call do nothing, which the output confirms. This matters becauseusingand a manualDisposecan both run. - Use after dispose throws
ObjectDisposedException.ObjectDisposedException.ThrowIfis the one-line standard guard, so a bug shows up as a clear error at the use site and not as a confusing failure from the underlying stream. - Disposing the writer flushes it. The file has both lines on disk the moment the
usingblock ends. Without it, buffered data can be lost. - The full pattern is for unsealed classes.
Dispose(bool disposing)lets a subclass add its own cleanup (seeAuditedFile) while the base class still guarantees its own. The subclass must callbase.Dispose(disposing). -
GC.SuppressFinalize(this)is in the publicDisposebecause subclasses may add a finalizer later. It tells the runtime the object needs no finalization, since cleanup has already happened. - You almost never write a finalizer. A finalizer is only for a class that directly holds an unmanaged handle. Wrapping a
StreamWriter(which already handles its own cleanup) never needs one. - The caller owns the lifetime with
using. The class design makes the correct usage easy, and the examples show that disposal order and exceptions are both handled.
Concept 11: JSON with System.Text.Json (custom converters and options)
What it is. JSON is the standard text format for exchanging data. Serialization turns an object into JSON text, and deserialization turns JSON text back into an object. System.Text.Json is the built-in, fast serializer in .NET. JsonSerializerOptions controls naming, formatting and enums, and a custom converter takes over when the default behaviour is not enough, as with polymorphic types.
The analogy: flat-pack furniture. Serializing is taking the finished wardrobe apart and putting the parts in a box with a parts list. Deserializing is assembling it again from the box. For a product that comes in several models, the box needs a label saying which model it is (a type discriminator), or the person assembling has no idea which instructions to use. A custom converter is the person who reads that label.
using System.Text.Json; using System.Text.Json.Serialization; var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, // Name -> name WriteIndented = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, // leave out null properties Converters = { new JsonStringEnumConverter() } // "Admin", not 2 }; var user = new User("Asha", 30, Role.Admin, null); string json = JsonSerializer.Serialize(user, options); Console.WriteLine(json); User? back = JsonSerializer.Deserialize<User>(json, options); Console.WriteLine($"Round trip equal: {back == user}"); // Reading is case-sensitive unless you ask otherwise var web = new JsonSerializerOptions(JsonSerializerDefaults.Web) { Converters = { new JsonStringEnumConverter() } }; User? loose = JsonSerializer.Deserialize<User>("""{"NAME":"Ravi","age":41,"role":"User"}""", web); Console.WriteLine(loose); // Bad input throws JsonException try { JsonSerializer.Deserialize<User>("{ not json }", options); } catch (JsonException) { Console.WriteLine("JsonException: that is not valid JSON"); } // Attributes control individual properties var account = new Account { Id = "a1", PasswordHash = "secret", Name = "Asha" }; Console.WriteLine(JsonSerializer.Serialize(account)); // Built-in polymorphism: a discriminator property says which subtype to build Animal[] animals = { new Dog("Rex"), new Cat("Tom", 9) }; string animalJson = JsonSerializer.Serialize(animals); Console.WriteLine(animalJson); Animal[]? restored = JsonSerializer.Deserialize<Animal[]>(animalJson); Console.WriteLine(string.Join(", ", restored!.Select(a => a.GetType().Name))); enum Role { User, Moderator, Admin } record User(string Name, int Age, Role Role, string? Nickname); class Account { public string Id { get; set; } = ""; [JsonIgnore] // never written out public string PasswordHash { get; set; } = ""; [JsonPropertyName("display_name")] // a different name in the JSON public string Name { get; set; } = ""; } [JsonPolymorphic(TypeDiscriminatorPropertyName = "kind")] [JsonDerivedType(typeof(Dog), "dog")] [JsonDerivedType(typeof(Cat), "cat")] abstract record Animal(string Name); sealed record Dog(string Name) : Animal(Name); sealed record Cat(string Name, int Lives) : Animal(Name); Output:
{ "name": "Asha", "age": 30, "role": "Admin" } Round trip equal: True User { Name = Ravi, Age = 41, Role = User, Nickname = } JsonException: that is not valid JSON {"Id":"a1","display_name":"Asha"} [{"kind":"dog","Name":"Rex"},{"kind":"cat","Lives":9,"Name":"Tom"}] Dog, Cat What is happening here:
-
JsonSerializerOptionsis where policy lives: camelCase names, indentation, skipping nulls, andJsonStringEnumConverterso enums read"Admin"and not2. Create the options once and reuse them, because building options repeatedly is slow. - Reading is case-sensitive by default.
JsonSerializerDefaults.Webturns on case-insensitive matching, which is why"NAME"still worked. - Bad JSON throws
JsonException. Never assume incoming JSON is valid. -
[JsonIgnore]leaves a property out and[JsonPropertyName]renames it, so the JSON shape can differ from your C# shape. -
[JsonPolymorphic]with[JsonDerivedType]is the built-in way to handle a base type with a few known subtypes. Thekindproperty tells the deserializer which subtype to create. - Positional records deserialize through their constructor, so immutable records work without extra code.
Practice question 11: a polymorphic list of shapes with a custom converter
Serialize and deserialize a polymorphic list of shapes (circles, rectangles, triangles) using a custom converter.
Solution
using System.Text.Json; using System.Text.Json.Serialization; var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, Converters = { new ShapeConverter() } }; List<Shape> shapes = [new Circle(2), new Rectangle(3, 4), new Triangle(6, 5)]; string json = JsonSerializer.Serialize(shapes, options); Console.WriteLine(json); List<Shape> restored = JsonSerializer.Deserialize<List<Shape>>(json, options)!; foreach (Shape shape in restored) { Console.WriteLine($"{shape.GetType().Name,-10} area {shape.Area():F2}"); } Console.WriteLine($"Round trip equal: {shapes.SequenceEqual(restored)}"); Console.WriteLine(); foreach (string bad in new[] { """[{"type":"hexagon","side":2}]""", """[{"radius":2}]""" }) { try { JsonSerializer.Deserialize<List<Shape>>(bad, options); } catch (JsonException ex) { Console.WriteLine($"JsonException: {ex.Message}"); } } public abstract record Shape { public abstract double Area(); } public sealed record Circle(double Radius) : Shape { public override double Area() => Math.PI * Radius * Radius; } public sealed record Rectangle(double Width, double Height) : Shape { public override double Area() => Width * Height; } public sealed record Triangle(double Base, double Height) : Shape { public override double Area() => 0.5 * Base * Height; } public sealed class ShapeConverter : JsonConverter<Shape> { public override Shape Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { using JsonDocument document = JsonDocument.ParseValue(ref reader); JsonElement root = document.RootElement; if (!root.TryGetProperty("type",...