Const String Interpolation in C# 10 and .NET 6

Text processing is the heart of every application building and it must be used. So today we will discuss Const String Interpolation in C# 10 and .NET 6. It makes the code more readable and more concise. So let’s get started.

If you want to improve StringBuilder performance in C# please follow our this post.

Click Me.

Const string implementation in C# 9:

In C# 9.0 we have to use the “+” operator for the const string concatenation. let’s see the example

public const string A = "Hi ";
public const string B = "How are ";
public const string C = "you";

public const string finalstring = A + ", " + B + C + "?";
//Hi, How are you?

Const String Interpolation in C# 10:

Now in C# 10, we can use the interpolated sign $ to combine our const strings.

public const string A = "Hi ";
public const string B = "How are ";
public const string C = "you";

public const string finalstring =$"{A}, {B}{C}?";
//Hi, How are you?

We can see the difference between both implementations and the major difference is code cleanness.

We can only perform this implementation if all strings are marked as const , It will not work if any of the strings is not const. Let me give you an example.

public const string constantstring = "A constant string";
public string notconst = "some not constant string";

//An exception will be thrown by this line.
public const string finalstring = $"{constantstring}. {notconst}"; 

This code will throw an exception and would not get you an output. So this interpolation feature only works with const strings.

Conclusion:

In this article, we have tried to cover const string interpolation which is the latest feature of C# 10. If you have any suggestions to make this content better please do not hesitate to comment below or contact us.

Leave a Reply

Your email address will not be published.