Formatting strings
In C#, the preferred method for formatting strings is using interpolated strings (string interpolation), which was introduced in C# 6.0. It provides a more readable and convenient syntax compared to other methods.
The $ character identifies a string literal
as an interpolated string. An interpolated string is a
string literal that might contain interpolation expressions.
When an interpolated string is resolved to a result string,
the compiler replaces items with interpolation expressions
by the string representations of the expression results.
You can embed expressions directly within a string by prefixing the string with a dollar sign ($). Here’s an example:
string name = "Alice";
int age = 30;
string greeting = $"Hello, my name is {name} and I am {age} years old.";Other Methods of String Formatting
While string interpolation is preferred, there are other methods you can use:
Composite formatting - String.Format Method:
string name = "Alice";
int age = 30;
string greeting = String.Format("Hello, my name is {0} and I am {1} years old.", name, age);Concatenation (plus operator +, plus equals operator +=, join strings):
string name = "Alice";
int age = 30;
string greeting = "Hello, my name is " + name + " and I am " + age + " years old.";StringBuilder (for more complex scenarios):
using System.Text;
StringBuilder sb = new StringBuilder();
sb.Append("Hello, my name is ");
sb.Append(name);
sb.Append(" and I am ");
sb.Append(age);
sb.Append(" years old.");
string[] values = ...
foreach (var value in values)
{
sb.Append(value);
}
var finalString = sb.ToString();Concatinating Collections
Using string.Concat method
string[] words = ...
var concatenated = string.Concat(words);Use string.Join method if a delimiter should
sepparate source strings.
string[] words = ...
string.Join(" ", words);Don't use the LINQ
.Aggregate((a, b) => a + b) method as it can
cause more allocations than other methods for concatenating
collections, as it creates an intermediate string for each
iteration. If optimizing performance is critical, consider
the StringBuilder class or the
string.Concat or string.Join
methods to concatenate a collection.
Links
- https://learn.microsoft.com/en-us/dotnet/csharp/how-to/concatenate-multiple-strings
- https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
- https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/string-interpolation
- https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/performance/interpolated-string-handler