How to enable the built-in .NET Analyzers

Previously you had to install and enable .NET Analyzers if you wanted to use it. Now, when you create a new project, it’s already installed and enabled by default (but you may want to change its settings). There are two main scenarios: If .NET Analyzers is already installed When you create a new project targeting … Read more

C# – Using ClassInitialize in a test class

You can use the ClassInitialize attribute on a method when you want to initialize something for all unit tests in a test class. This initialization method only runs once and is ran before any of the unit tests. Here’s an example of how to add ClassInitialize: Note: ClassCleanup is the opposite of ClassInitialize. It runs … Read more

Install and configure a Windows Service from the command line

In this article I’ll show how to install and configure a Windows Service, query its status and properties, and then how to uninstall it. I’ll be using the command line utilities installutil.exe and sc.exe to install and configure the service. Add a service installer class to your Windows Service project In order to use installutil.exe … Read more

C# – DataGridView index out of range exception

Problem When you’re using WinForms and click a DataGridView column header, you get an exception like this: Index was out of range. Must be non-negative and less than the size of the collection. This problem is caused by the column header “row” triggering a click event (such as CellContentClick) with event args containing RowIndex of … Read more

C# – SQL Bulk Insert with SqlBulkCopy

When you need to insert multiple rows into the database, consider doing a Bulk Insert instead of inserting one row at a time. Bulk Insertions are up to 20x faster than executing SQL Insert repeatedly. The simplest way to do a SQL Bulk Insert is by using the built-in SqlBulkCopy (from System.Data.SqlClient) with a DataTable. … Read more

Refactoring the Nested Conditionals code smell

Nested conditionals are a code smell because they make the code harder to understand. They tend to grow more and more complicated over time because developers will keep adding conditions and more levels of nesting. The deeper the nesting, the more time it’ll eventually take to refactor it. Code Smell: Nested conditionals.Definition: A conditional block … Read more

C# – Waiting for user input in a Console App

The following code shows how to wait for user input in a Console App: When the user types something in and presses the Enter key, Console.ReadLine() will return what they typed. Console.ReadLine() vs Console.ReadKey() Console.ReadLine() waits for the user to press Enter, and then returns everything they typed in. Console.ReadKey() returns individual key presses. It … Read more

C# – Create a custom JsonConverter for System.Text.Json

Most of the time System.Text.Json will get you want you want. You can pass in options to control JSON serialization and deserialization to a certain extent. But sometimes you’ll run into scenarios where you need to customize how it handles a specific type. This is where JsonConverter comes in. You can customize serialization / deserialization … Read more

JsonException: A possible object cycle was detected

When you use System.Text.Json.JsonSerializer to serialize an object that has a cycle, you get the following exception: System.Text.Json.JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 0. In .NET 6+, you can … Read more

C# – How to handle nulls with SqlDataReader

SqlDataReader returns a DBNull object when a column is null. This isn’t the same as a C# null. You can check if the column is null by comparing it with DBNull.Value or by using SqlDataReader.IsDBNull(). Here’s an example showing these two ways of checking if a column is null: After checking if the column is … Read more

C# – Use StringAssert when testing a string for substrings

When you’re testing if two strings are equal, you can simply use Assert.AreEqual(). When you’re testing if a string contains a substring or a pattern, typically developers use Assert.IsTrue() with a substring method or regex. You should use StringAssert instead, because it gives better failure messages. Note: StringAssert is nice because it’s a built-in class. … Read more

C# – Using XmlSerializer to serialize

Here’s how to serialize an object into XML using XmlSerializer: You must add the [Serializable] attribute to the class you want to serialize: Here’s an example of creating an Author object and feeding it to the serializer: This outputs the following XML: This example showed how to use XmlSerializer with all the default settings. In … Read more

C# – Serialize a tuple to JSON

When you serialize a tuple to JSON, it uses the the underlying ValueTuple’s field names – Item1 and Item2. It doesn’t matter if you’re using a named tuple, it won’t use the names you specified in the tuple declaration. This behavior is the same with Newtonsoft and System.Text.Json. Here’s an example of serializing a named … Read more

TargetParameterCountException: Parameter count mismatch

When you are using reflection to call a method, you may run into this exception: System.Reflection.TargetParameterCountException: Parameter count mismatch. This exception is straightforward – you aren’t passing in the correct number of parameters to MethodInfo.Invoke(). This article shows three different cases where you might run into this exception when using reflection. Using reflection to invoke … Read more

C# – How to create a custom exception

To create a custom exception, create a subclass of the Exception class, like this: Then throw it just like you would any other exception, like this: It’s a good idea to call the base constructor from your constructor and pass in your custom error message. If this exception is unhandled, or if you are logging … Read more

.NET Core – Check which OS you’re running in

.NET Core enables you to write cross-platform C# code. Sometimes you’ll want to do things differently depending on the OS you’re running in. You can use RuntimeInformation.IsOSPlatform() to figure out which OS you’re in. Here’s an example of using this to see if you’re running in Windows: Example – Loading a different native library depending … Read more

Querying JSON in SQL Server

In SQL Server 2016, Microsoft added support for handling JSON data: The JSON API in SQL Server is well-suited for simple scenarios where you only need to do basic querying and manipulation. For advanced querying, the SQL Server JSON API gets complicated and hard to use, so you may want to look into other options. … Read more