C# – Merge two dictionaries in-place

When you merge two dictionaries, you can either merge them in-place, or create a new dictionary and copy the values over to it. The following extension method does an in-place merge of two dictionaries. It loops through items in the right dictionary, adding them to the left dictionary. When duplicate keys exist, it’s keeping the … Read more

C# – Fill a dropdown with enum values

When you need to show enum values in a dropdown (ComboBox control with DropDownStyle=DropDown), it’s a good idea to automatically populate the list, instead of manually setting all of the values. To fill the dropdown with the enum’s values, set the DataSource to Enum.Values(), like this: Read more about how to show the enum’s Description … Read more

System.BadImageFormatException: Could not load file or assembly

Problem – Can’t load assembly When you have one assembly trying to use another assembly, and they don’t have matching bitness (x64 or x86), then you’ll get an exception: either BadImageFormatException or FileLoadException. If your project references another assembly, and the bitness doesn’t match, you’ll get this exception: System.BadImageFormatException: ‘Could not load file or assembly … Read more

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

Using sp_msForeachTable in SQL Server

You can use the sp_msForeachTable stored proc in SQL Server to execute a query/command against all tables in the database. To give you an idea about how to use this, here’s an example of using it to do a SELECT query against all tables: Internally, sp_msForeachTable gets all user table names (from dbo.sysobjects) and opens … 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