Concatenate strings using C# with Example



Concatenate strings using C# with Example

System.Text.StringBuilder 
Concatenating strings using a StringBuilder can offer performance advantages over simple string concatenation 
using +. This is due to the way memory is allocated. Strings are reallocated with each concatenation, StringBuilders 
allocate memory in blocks only reallocating when the current block is exhausted. This can make a huge difference 
when doing a lot of small concatenations. 
StringBuilder sb = new StringBuilder(); 
for (int i = 1; i <= 5; i++) 
{ 
sb.Append(i); 
sb.Append(" "); 
} 
Console.WriteLine(sb.ToString()); // "1 2 3 4 5 " 
Calls to Append() can be daisy chained, because it returns a reference to the StringBuilder: 
StringBuilder sb = new StringBuilder(); 
sb.Append("some string ") 
.Append("another string"); 

0 Comment's

Comment Form

Submit Comment