I was googling for best c# string concatenation, and I found this at microsoft c# code conventions: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions
Use the
+
operator to concatenate short strings, as shown in the following code:
string displayName = nameList[n].LastName + ", " + nameList[n].FirstName;
But I really prefer (String.Format
) "$
" for more readability IMHO:
string firstName = "MyName";
string lastName = "MyLastName";
string displayName = $"{lastName}, {firstName}";
Console.WriteLine(displayName); // "MyLastName, MyName"
Can you tip me which one do you think is better one? or is just about personal preference?
Thanks!
Use StringBuilder
for the best performance.
String.Format
is also good but not an exact replacement for "+" operator on string.
StringBuilder builder = new StringBuilder();
// Append to StringBuilder.
for (int i = 0; i < 10; i++)
{
builder.Append(i).Append(" ");
}
Console.WriteLine(builder);
Remember to import namespace:
using System.Text;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With