Formatting the return string

Two Fer
Two Fer in C#

There are various ways in which you can format the return string.

Option 1: string interpolation

String interpolation was introduced in C# 6.0 and is the most idiomatic way to build up a string with one more variable parts.

$"One for {name}, one for me.";

Option 2: string concatenation

As there are few variable parts in the returned string (just one), regular string concatentation works well too:

"One for " + name + ", one for me.";

It is slightly more verbose than string interpolation, but still completely reasonable.

Option 3: using string.Format()

Before string interpolation was introduced in C# 6, string.Format() was the go-to option for dynamically formatting strings.

string.Format("One for {0}, one for me.", name);

String interpolation is in most ways superior to string.Format(), so it is no longer idiomatic to use string.Format().

Option 4: using string.Concat()

Another option is string.Concat():

string.Concat("One for ", name, ", one for me.");

Conclusion

String interpolation is the preferred and idiomatic way to format strings. String concatentation is absolutely a viable option too, as there is only one variable part. Both string.Format() and string.Concat() are functionally equivalent, but more cumbersome to read and there we don't recommend using them.

8th May 2024 · Found it useful?