C# – Check if a nullable bool is true

You can’t use nullable bools (bool?) exactly like regular bools, because they aren’t the same thing. When you try to use them like regular bools, you run into compiler errors and runtime exceptions. Instead, you have to explicitly compare the nullable bool with true/false. Here’s an example of checking if a nullable bool is true … Read more

C# – Use string interpolation instead of string.Format

Using string.Format() is error prone and can lead to runtime exceptions. Using string interpolation prevents these problems (and it’s more readable). This article shows the two common mistakes you can make when using string.Format(), resulting in runtime exceptions, and shows how you can use string interpolation to prevent these problems. 1 – FormatException: Format string … Read more

C# – Reuse JsonSerializerOptions for performance

Reusing JsonSerializerOptions (from System.Text.Json) is optimal for performance. It caches type info, which results in a 200x speedup when it deals with the type again. Therefore, always try to reuse JsonSerializerOptions. I’ll show a speed comparison of serializing with and without reusing JsonSerializerOptions. Measuring the performance gains of reusing JsonSerializerOptions To measure the performance gains … Read more

Newtonsoft: Self referencing loop detected for property

Problem When you try to serialize an object using Newtonsoft.Json and there’s a circular reference, you get the following exception: Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property Here’s an example of code that results in this exception: The Parent object references the Child object, which references the Parent object. Hence, a circular reference (aka a … Read more

C# – How to call a static method using reflection

You can use reflection to get properties or methods programmatically at runtime. Here’s an example of calling a static method with reflection: Note: This static method is parameterless. If you have parameters, you have to pass them in like this .Invoke(null, param1, param2). Example – passing static method names to a parameterized unit test With … Read more

InvalidArgument=Value of ‘0’ is not valid for ‘SelectedIndex’

Problem Let’s say you’re initializing a ComboBox like this: And you get the following exception: System.ArgumentOutOfRangeException: ‘InvalidArgument=Value of ‘0’ is not valid for ‘SelectedIndex’. (Parameter ‘value’)Actual value was 0.’ You’re getting this exception because the DataSource you’re binding to is empty. Solution Are you expecting there to always be data? If you’re expecting there to … Read more

C# – Hex string to byte array

This article shows code for converting a hex string to a byte array, unit tests, and a speed comparison. First, this diagram shows the algorithm for converting a hex string to a byte array. To convert a hex string to a byte array, you need to loop through the hex string and convert two characters … Read more

C# – How to copy an object

In this article I’ll explain how to copy an object. I’ll explain the difference between shallow and deep copying, and then show multiple ways to do both approaches for copying objects. At the end, I’ll show a performance and feature comparison to help you decide which object copying method to use. Shallow copy vs Deep … Read more

C# – How to use enum flags

Enum flags allow you to put multiple values in an enum variable/parameter. This is a nice alternative to the problem of having to pass around a ton of bools . You set multiple values by bitwise ORing them together. Here’s an example: In this article, I’ll show how to create and use enum flags. Use … Read more

JsonException: The JSON value could not be converted to Enum

When you’re using System.Text.Json to deserialize JSON that contains the string representation of an enum, you get the following exception: System.Text.Json.JsonException: The JSON value could not be converted to <Enum Type> The following JSON would cause this exception. Conference is an enum, and this is using the string representation “NFC” instead of the numeric value … Read more

C# – Case sensitivity in JSON deserialization

By default Newtonsoft does case insensitive JSON deserialization and System.Text.Json does case sensitive JSON deserialization. Case sensitivity comes into play when a JSON string is being deserialized into an object. If you’re using case sensitive deserialization, then keys in the JSON string must match type names exactly, otherwise it won’t deserialize the class/property with the … Read more

C# – Conditionally catch exceptions with filtering

You can use exception filtering to conditionally catch exceptions, like this: Note: This feature was added in C# 6. Any SqlException that doesn’t meet the condition specified in the when clause will not be caught. Previously, without exception filtering, you’d have to handle that scenario in the catch block and rethrow, like this: Exception filtering … Read more

System.Text.Json can’t serialize Dictionary unless it has a string key

Before .NET 5, the built-in JSON serializer (System.Text.Json) couldn’t handle serializing a dictionary unless it had a string key. Here’s an example running in .NET Core 3.1 to show the problem. This is initializing a dictionary with values and then attempting to serialize it. This results in exception: System.NotSupportedException: The collection type ‘System.Collections.Generic.Dictionary`2[System.Int32,System.String]’ is not … Read more

C# – How to use Assert.ThrowsException

Use Assert.ThrowsException<T>() in a unit test to verify that the code throws a specific type of exception. Here’s an example of asserting that ArgumentNullException is thrown: You specify the type of exception you’re expecting and then pass in a lambda that calls the code you’re testing. The assertion succeeds if and only if the code … Read more

C# – Check if a directory is empty

The simplest way to check if a directory is empty is by calling Directory.EnumerateFileSystemEntries(). If this doesn’t return anything, then the directory doesn’t have any files or subdirectories (folders), which means it’s empty. Here’s an example: Another situation to consider is when a directory has no files but might have empty subdirectories (folders). You can … Read more

How to use BackgroundService in ASP.NET Core

You can use a hosted BackgroundService in ASP.NET Core for two purposes: In this article, I’ll show how to create and register a hosted BackgroundService. In this example, it periodically pings a URL and logs the results. 1 – Subclass BackgroundService The first step is to subclass BackgroundService: In this example, we’ll create a background … Read more

Common Newtonsoft.Json options in System.Text.Json

If you’re switching from Newtonsoft.Json to System.Text.Json (or vice versa), you may be wondering how to specify the common options you’re used to using in Newtonsoft. For example, how do you specify the equivalent of Newtonsoft.Json.Converters.StringEnumConverter in System.Text.Json? The following table shows a few common serialization options used in Newtonsoft.Json and their equivalents in System.Text.Json. … Read more

Error: Synchronous operations are disallowed

Problem When you try to do a synchronous IO operation in ASP.NET Core (such as writing to a file), you get the following exception: System.InvalidOperationException: ‘Synchronous operations are disallowed. Call WriteAsync or set AllowSynchronousIO to true The reason you’re getting this is because server option AllowSynchronousIO is false. Starting in ASP.NET Core 3.0, this is … Read more

C# – Using Channel as an async queue

The Channel class (from System.Threading.Channels) is a non-blocking async queue. It implements the producer-consumer pattern, which has two parts: Compare this with using BlockingCollection, which is a blocking concurrent queue. In this article, I’ll show how to use a Channel. 1 – Create the Channel The first step is to create the Channel object. Here’s … Read more

ASP.NET – Async SSE endpoint

Server-Sent Events (SSE) allow a client to subscribe to messages on a server. The server pushes new messages to the client as they happen. This is an alternative to the client polling the server for new messages. In this article I’ll show how to implement the messaging system shown in the diagram below. This uses … Read more

C# – Async Main

The Async Main feature was added in C# 7.1 and works with all overloads of the Main() method. To make the Main() method async, add async Task to the method signature, like this: This is syntax sugar that compiles down to calling GetAwaiter().GetResult() on whatever you’re awaiting. In other words, it’s equivalent to doing the … Read more

C# – Cannot use a lambda expression as an argument to a dynamically dispatched operation

Problem You are trying to use a lambda expression on a dynamic object and get the following compiler error: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. As an example, the following code causes this error: Solution Cast the … Read more