Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# string concatenation best practice [duplicate]

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!

like image 771
Ferus7 Avatar asked Oct 12 '25 08:10

Ferus7


1 Answers

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;
like image 134
Habeeb Avatar answered Oct 14 '25 04:10

Habeeb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!