C# – How to use format strings with string interpolation

Interpolated strings have the following structure: {variable:format}. Typically you exclude the format, so they normally look like this: $”My name is {name}”. Here’s how to use format strings with an interpolated string: This outputs the following: This is the equivalent of using string.Format() like this: Read more about why you should use string interpolation instead … Read more

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

C# – Handle a faulted Task’s exception

When a Task throws an exception and stops running, it has faulted. The question is, how do you get the exception that was thrown from the faulted Task? This depends on if you’re awaiting the Task or not. This article shows how to handle a faulted Task’s exception in two scenarios: when you’re awaiting the … Read more

C# – Check if an IP range is valid

Given an IP range as a starting IP address and an ending IP address (as strings, like from user input or a config file), you can check if the IP range is valid by doing the following steps: Here’s an example. Let’s say you’re given starting IP “192.168.0.1” and ending “192.168.0.11”. The following table shows … Read more

C# – Set operations with Linq

In this article, I’ll explain four set operations – intersection, union, difference, and symmetric difference – and how to perform these operations using Linq methods (such as Intersect()). These methods work on any type that implements IEnumerable – such as lists, arrays, and sets. Set intersection with Intersect() The intersection of set A {1,2} and … Read more

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

Problem In a WinForms project, if you try to call Invoke/BeginInvoke before the window handle is created, you’ll get the following exception: System.InvalidOperationException: Invoke or BeginInvoke cannot be called on a control until the window handle has been created Because this exception happens while the form is initializing, it typically results in the form not … Read more

NLog – Split trace logging into its own file

This article explains how to configure NLog so that trace-level log messages go to their own file. This is useful because trace logging involves logging every method call for short-term troubleshooting, leading to very large log files. This approach only requires modifying the nlog.config file, and doesn’t require any code changes. In the end, all … Read more

C# – How to read configuration from appsettings.json

The appsettings.json file is a convenient way to store and retrieve your application’s configuration. You can add it to any project and then use the Microsoft.Extensions.Configuration library to work with it. Since appsettings.json is just a JSON file, you can add any section / values you want (this is easier than working with XML-based app.config … Read more

C# – Duplicate ‘AssemblyVersion’ attribute

Problem You’re trying to add the AssemblyVersion attribute to your project, like this (or perhaps you’re trying to auto-increment the version): And you get the following compiler errors: Error CS0579 Duplicate ‘AssemblyVersion’ attribute Error CS0579 Duplicate ‘AssemblyFileVersion’ attribute But you don’t see these attributes anywhere else in your project. Solution The problem is Visual Studio … Read more

How to generate XML documentation and include it in a nuget package

XML documentation comments serve two purposes: In this article I’ll show how to automatically generate an XML documentation file and how to include it in a nuget package. 1 – Write the XML documentation comments in your code I have a method called MergeInPlace() (which merges two dictionaries in-place). To explain what this is doing … Read more

C# – Read a custom config section from app.config

In this this article, I’ll show the simplest to get a custom config section from app.config and load it into your own config class. You can implement IConfigurationSectionHandler and use ConfigurationManager.GetSection() to do this. I’ll show the steps below. 1 – Add a custom config class The first step is to create a class that’ll … Read more

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