Just like the previous example of File-Level Namespaces, the new Const Interpolated Strings feature aims to make our code more readable and more concise.

Current Implementation

When using const strings in C# 9.0 and earlier, we could only concatenate them using the + operator:

public const string Greeting = "Hello ";
public const string Title = "Ms. ";
public const string LastName = "Keating";

public const string Salutation = Greeting + ", " + Title + LastName + "!";
//Hello, Ms. Keating!

New Implementation

In C# 10, we are now allowed to use the interpolated string operator $ to combine const strings:

public const string Greeting = "Hello ";
public const string Title = "Ms. ";
public const string LastName = "Keating";

public const string Salutation 
	= $"{Greeting}, {Title}{LastName}!";

As you can imagine, this cleans up our code nicely.

Other Considerations

The major thing to know about this feature is that it only works if all the strings used in the interpolated string are themselves marked const. The following code, therefore, will throw exceptions when compiled.

public const string Constant = "This is a constant string";
public string NotConstant = "This is NOT a constant string";

//An exception will be thrown by this line.
public const string InterpolatedConst = $"{Constants}. {NotConstant}"; 

Further, per the official Microsoft documentation, the interpolated const values cannot be numeric, since:

"The placeholder expressions can't be numeric constants because those constants are converted to strings at runtime."

So, in reality, this feature only works with const string values.

Demo Project

Const interpolated strings are already included in the preview of C# 10.0. Check out my demo project here:

GitHub - exceptionnotfound/CSharp10Features
Contribute to exceptionnotfound/CSharp10Features development by creating an account on GitHub.

You will need Visual Studio 2022 Preview to run this project.

Happy Coding!