Coding Faster With The dotNetTips Utility - StringBuilder Extensions

Recently, I was looking at the source code for Entity Framework Core and found a few interesting extension methods for the StringBuilder class. So I moved the ones I liked to my open-source project called dotNetTips.Utility.Standard.Extensions and is part of the NuGet package too.

Appending Bytes

If you want to combine an array of byte values in StringBuilder, you can use the AppendBytes() extension method below.
  1. var sb = new StringBuilder();  
  2. var byteArray = RandomData.GenerateByteArray(sizeInKb: 1);  
  3. sb.AppendBytes(byteArray);  
Here is the result of the above code.

Appending Values

There are many times that values from a collection need to be combined into a delimited string. You can use the AppendValues() method as shown below.
  1. var sb = new StringBuilder();  
  2. var values = RandomData.GenerateWords(count: 5, minLength: 5, maxLength: 7);  
  3. sb.AppendValues(",", values);   
Here is the result from the code above.
BgMes, oGsreY, kpcJ^, bAA]U, Jov`rE
This method is overloaded to accept the following types for the collection of strings: IEnumerable<string>, IEnumerable<T>.

Appending Values using an Action

If you want to combine values from a collection using a custom action which allows for more flexibility, then using ApendValues() as shown below will do the trick.
  1. var sb = new StringBuilder();  
  2. var values = RandomData.GenerateCoordinateCollection<Coordinate>(count: 5);  
  4. sb.AppendValues(", ",values, (sb, person) =>  
  5. {  
  6.     sb.Append(person.X);  
  7.     sb.Append(ControlChars.Colon);  
  8.     sb.Append(person.Y);  
  9. });   
Here is the result from the code above.
1598221432:-705467152, -616323156:-1857438448, -1686969361:1572163353,
-1328828514:-1887231033, 53532470:-120489468


I hope you will try these StringBuilder extension methods in your code. Just install the NuGet package and you are ready to go!

McCarter Consulting
Software architecture, code & app performance, code quality, Microsoft .NET & mentoring. Available!