Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

StringBuilder add Separator between appended Strings

I am using StringBuilder for logging errors and messages conveniently, and its instance will be pass around methods. My goal is to append errors together, separated by comma, such as "Duplicated ID, Invalid cost, Unsupported Service for account". However, I couldn’t find any supported method that separates each appended string with a separator, such as:

//Maybe something like a default separator?
errorBuilder.DefaultSeparator=',';
errorBuilder.Append("Duplicated ID");
errorBuilder.Append("Invalid cost");
errorBuilder.Append("Unsupported Service for account");
Log(errorBuilder.ToString())

errorBuilder.Append(validateID(id) + ", ") isn’t ideal since it requires extra effort to remove the comma anywhere before errorBuilder.ToString() is called.

I am aware that I could just pass a List around and use String.Join(",", "List.ToArray()") or StringBuilder.AppendJoin or create a custom class, but I wonder if I can use the native StringBuilder to achieve this goal?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am using .NET Framework 4.7.2.

Note: I would be Appending different messages or errors at different places, based on different scenarios and input, as a normal Error Tracer would.

>Solution :

No, there’s no functionality in StringBuilder that will make Append automatically put a comma between elements that you append.

I want to use the native StringBuilder because it is already been passed around many methods, changing it requires some effort.

It sounds like your code got tightly coupled to the wrong abstraction. Fixing the problem will probably require some effort, but it’s better to do it now than to continue using the wrong model.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading