System.Text.Json – How to customize serialization with JsonConverter

Most of the time JsonSerializer will get you want you want. You can pass in options to control serialization to a certain extent. But sometimes you’ll run into scenarios where you need to customize how it handles serialization for a specific type. This is where JsonConverter comes in. To customize serialization for a specific type, … Read more

C# – Using SqlDataReader to process multiple result sets

In this article I’ll show how to use the SqlDataReader ADO.NET class in two scenarios involving multiple result sets: Batches – When you execute multiple SELECTs in a single query. Each SELECT returns a different result set. You use a single reader to process the batch. Nested Queries – When you use multiple SqlDataReaders on … Read more

System.InvalidOperationException: Serializer options cannot be changed once serialization or deserialization has occurred

Problem When using System.Text.Json, it’s a good idea to reuse JsonSerializerOptions objects. This leads to a massive 200x speedup in subsequent calls to the serializer. The downside is you can’t change properties on the options object after you’ve passed it in a Serialize()/Deserialize() call. You’ll get the exception: System.InvalidOperationException: Serializer options cannot be changed once … Read more

.NET JsonSerializer is over 200x faster if you reuse JsonSerializerOptions

When you serialize an object using the built-in .NET JsonSerializer (System.Text.Json), reusing the JsonSerializerOptions object is 200x faster than serializing with a new options object each time. The JsonSerializerOptions object must have some kind of internal caching mechanism that makes subsequent serializations on the same type significantly faster. Note: Creating the new JsonSerializerOptions object adds … Read more

C# – How to use enum flags to pass multiple options as a single parameter

When you need to pass multiple options into a method, normally you would add a bool flag for each parameter, like: Not only is using bool flags a bit of a code smell, but when this list of parameters gets too big, you’ll probably want to refactor by moving the bool flags into an options … Read more