C#

C# deep dive: IDisposable, JSON, unit testing and dependency injection

DEV Community: #csharp Manohari Jayachandran
C#

The second half of day four in a six-day C# series, covering resource cleanup, System.Text.Json configuration, unit testing and dependency injection with practice projects. Intermediate developers who already write code daily can use it to close the gaps they skipped over.

Key points

  • A using declaration disposes at the end of scope, a using block at the closing brace, exceptions included.
  • A sealed class holding only managed resources needs just a simple Dispose; Dispose(bool) exists for inheritance.
  • ObjectDisposedException.ThrowIf turns use-after-dispose into a clear one-line failure at the call site.
  • Build JsonSerializerOptions once and cache them; recreating options on every call is a known cost.
  • JsonSerializerDefaults.Web enables case-insensitive reads, while the default deserialization is case-sensitive.
  • JsonPolymorphic and JsonDerivedType restore known subtypes through a discriminator such as kind.

Why it matters

Most of these topics are already in daily use but often at copy-paste depth: carrying the full Dispose(bool) pattern into sealed classes, rebuilding JsonSerializerOptions per request, or forgetting that deserialization is case-sensitive by default. The post works well as a checklist for correcting those reflexes.

It is not news, though, just one instalment of a teaching series. If your production code already follows these patterns, you will not learn much. Before reading, check which of your own types implement IDisposable and where your JsonSerializerOptions instances are created; that is where the payoff is.

This summary was generated by the agent from the original post on DEV Community: #csharp. The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message