StringBuilder: char constructor #46052
-
After (painfully) realizing that certain public StringBuilder(char? value) This is a simplified version of the code that brought me here: var str = "ABC";
var sb = new StringBuilder(str.Last());
Console.WriteLine($"-->{sb.ToString()}<--"); Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 7 replies
-
I feel like this isn't a common enough situation to justify adding a new API. I'm assuming you need a If you need to allocate a single-character var str = "ABC";
var sb = new StringBuilder(1);
sb.Append(str.Last()); |
Beta Was this translation helpful? Give feedback.
-
I would have said that initializing a I still think that it would be great to avoid the current behavior difference beween PD: as stated, that was a simplified version of the code, the |
Beta Was this translation helpful? Give feedback.
-
Feel free to open issue proposing an analyzer. |
Beta Was this translation helpful? Give feedback.
-
What unfortunately happened was the Unfortunately that means adding a new constructor would break existing code. (Even if that code is probably incorrect.) This was proposed before as #20848 and was rejected. You can watch the design review for their reasoning here: https://youtu.be/JdaQ2RP2tqM?t=6187 I think this could be something that could make sense as an analyzer. Possibly even as one of the analyzers in |
Beta Was this translation helpful? Give feedback.
What unfortunately happened was the
char
was implicitly cast toint
. So it called the initial-capacity constructor.Unfortunately that means adding a new constructor would break existing code. (Even if that code is probably incorrect.)
This was proposed before as #20848 and was rejected. You can watch the design review for their reasoning here: https://youtu.be/JdaQ2RP2tqM?t=6187
I think this could be something that could make sense as an analyzer. Possibly even as one of the analyzers in
Microsoft.CodeAnalysis.NetAnalyzers
.