Simple Way to Create Delimited String

Created: December 21, 2014 Tagged As: C#, Language Share:

A common, yet inefficient way to create a delimited string is to declare a string variable and continuously append delimiters and values to it. This is grossly inefficient since strings are immutable and new memory is allocated for each concatenation. This method also involves a lot of repetitive code that. Here is a much more efficient way:

public static void AppendToken(this StringBuilder sb, string Token, char Separator)
 if (string.IsNullOrEmpty(Token)) return;
 if (sb.Length > 0)
In use:

StringBuilder sbExample = new StringBuilder();
sbExample.AppendToken("string 1"' ');
sbExample.AppendToken("string 2"' ');
sbExample.AppendToken("string 3"' ');


string 1, string 2, string 3


See, it's as easy as 123!