What’s New in C# 10: Create Constants Using String Interpolation

This is part of a series on the new features introduced with C# 10.

Prior to C# 10 if you wanted to create a const that was made up from other constants you had to add the string fragments togeter, for example (C# 9):

const string SupportedCurrencyCodes = "GPB, USD, AUD";
const string Copyright = "Jason Roberts";
const string TwitterSupportAccount = "@RobertsJason";

const string AboutMessage = "Currency codes supported '"
                                    + SupportedCurrencyCodes
                                    + "'. Support via Twitter: " + TwitterSupportAccount
                                    + ". Copyright 2022 " + Copyright + ".";

This is a bit messy and hard to read.

From C# 10 you can create a constant using string interpolation as you would do with a normal variable, for example in C# 10:

const string SupportedCurrencyCodes = "GPB, USD, AUD";
const string Copyright = "Jason Roberts";
const string TwitterSupportAccount = "@RobertsJason";

const string AboutMessage = $"Currency codes supported '{SupportedCurrencyCodes}'. Support via Twitter: {TwitterSupportAccount}. Copyright 2022 {Copyright}.";

Even thought the line is a bit longer (horizontally) it is easier to understand the entire string. One caveat with this is that all the values in the braces have to be string contants - you can’t use number constant for example in a const interpolated string.

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.

SHARE:

Add comment

Loading