Two popular classes that you will use frequently when working with strings in .NET Core are the String and StringBuilder classes. You should be aware of the best practices when using both these classes to build applications that minimize allocations and are highly performant. This article discusses the best practices we can follow when working with strings in C#.

To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here. Note we’ll also use BenchmarkDotNet to track performance of the methods. If you’re not familiar with BenchmarkDotNet, I suggest reading this article first.

Benchmarking code is essential to understanding the performance of your application. It is always a good approach to have the performance metrics at hand when you’re optimizing code. The performance metrics will also help you to narrow in on the portions of the code in the application that need refactoring. In this article they will help us understand the performance of string operations in C#.

Create a .NET Core console application project in Visual Studio

First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new .NET Core console application project.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Click Create.

We’ll use this project to work with the String and StringBuilder classes in the subsequent sections of this article.

Install the BenchmarkDotNet NuGet package

To work with BenchmarkDotNet you must install the BenchmarkDotNet package. You can do this either via the NuGet Package Manager inside the Visual Studio 2019 IDE, or by executing the following command in the NuGet package manager console:

Copyright © 2021 IDG Communications, Inc.