Repository navigation
Fix 'StringBuilder' initialization - #3458
Conversation
| if (errors.Count > 0) | ||
| { | ||
| var allErrors = new StringBuilder('\n'); | ||
| // Bug: don't use '\n' ('char' convert implicitly to 'ushort' and 'int' and initialize 'StringBuilder' size) |
There was a problem hiding this comment.
Can you change Bug: to Note: please? Bug: usually indicates there is a potential bug here that needs to be revisited.
| if (errors.Count > 0) | ||
| { | ||
| var allErrors = new StringBuilder('\n'); | ||
| // Note: don't use '\n' ('char' convert implicitly to 'ushort' and 'int' and initialize 'StringBuilder' size) |
There was a problem hiding this comment.
While the comment is interesting, I think it's a distraction from understanding the code.
There was a problem hiding this comment.
This should only protect against reverting.
(Feel free to approve the comment.)
There was a problem hiding this comment.
I still don't think it's helpful - education of weird aspects of an api don't really belong in random places in code unless it's extremely likely that you'll hit the problem again.
In this case, I think it's unlikely.
There was a problem hiding this comment.
What is the preferred solution do you see here? Remove the comment?
Complete solution I believe should be in CoreFX or in the compiler.
Also we can do here:
var allErrors = new StringBuilder();
allErrors.Append('\n'); There was a problem hiding this comment.
I think removing the comment is sufficient as it's mostly obvious that a string argument initializes the instance.
If you'd like to make other improvements though - it's good practice to pass the estimated capacity when constructing a StringBuilder to minimize extra allocations, but only if it's easy to estimate (e.g. use a constant, avoid computing the "estimate").
And calling Append with a char might be slightly better than passing a string to the constructor, but honestly the performance here doesn't really matter.
There was a problem hiding this comment.
Jason Shirk (@lzybkr) Thanks for great comment!
Here we cannot use a constant, the capacity is ~(1+ 2 * errors.Count).
Do it make sense to open CoreFX issue to add new constructor for StringBuilder ?
StringBuilder new(char value)
There was a problem hiding this comment.
To be clear, a reasonable estimate is probably better than the default, and constant, or easily computed value, e.g. count*80 our something like that is reasonable. But again, it really doesn't matter here.
As for a CoreFX issue - it's up to you. I feel like they might discuss it, but reject it in favor of fewer APIs because it should if you properly test, you'd notice your character is missing.
There was a problem hiding this comment.
Close #3457