SHARE:

Introducing C# 10: Constant interpolated strings

Introduction

C# is still evolving, this time with C# 10 we will focus on constants. Before C# 10 it was possible to concatenate strings, the string interpolation functionality existed but did not allow to have interpolated string constants. this is now possible with C# 10 for readability reasons. Let’s look at an example.

Example

Before C# 10, string constants were concatenated like this:

using System;
namespace DemoCsharp
{
public class Demo
{
private const string scheme = "https";
private const string LoginUri = "login";
private const string HomeUri = "home";
private const string dev = scheme + "://localhost:5001";
private const string LoginUriDev = dev + "/" + LoginUri;
private const string HomeUriDev = dev + "/" + "myaccount" + "/" + HomeUri;
}
}
view raw Demo.cs hosted with ❤ by GitHub

Since C# 10, string interpolation can be used to create more readable constant strings:

using System;
namespace DemoCsharp10
{
public class Demo
{
private const string scheme = "https";
private const string LoginUri = "login";
private const string HomeUri = "home";
private const string dev = $"{scheme}://localhost:5001";
private const string LoginUriDev = $"{dev}/{LoginUri}";
private const string HomeUriDev = $"{dev}/myaccount/{HomeUri}";
}
}
view raw Demo.cs hosted with ❤ by GitHub

As Microsoft said it, “The placeholder expressions can’t be numeric constants because those constants are converted to strings at runtime. The current culture may affect their string representation”. So that feature can’t be used on numeric constants.

According to me, it’s definitely more readable, and I love to use constant strings like this. 🙂

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.