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; | |
} | |
} |
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}"; | |
} | |
} |
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.