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?
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.
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.