Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why didn't microsoft overload the += operator for stringbuilder? [closed]

Tags:

c#

For the StringBuilder class, why not overload the += operator instead of a using a unique .Append() method?

Append() only concatenates strings so why did they not just overload += operator like so:

StringBuilder sb = new StringBuilder();
sb += "My string";

Is it a case of efficiency? Is it a case of convention or intuitiveness?

Thanks,

like image 820
PeonProgrammer Avatar asked Feb 21 '14 02:02

PeonProgrammer


1 Answers

Arithmetical operations should be limited to types that act like arithmetical values. It is bad enough that the sum of two strings is a third string. Conflating the addition operation with string concatenation is a questionable choice because string concatenation obeys very few of the rules of addition; in particular, a + b != b + a.

But to go there for string builders -- which are by definition mutable state and not arithmetical values -- is horrid. The sum of two things should be a third thing that differs from the two summands. That is, a += b must have the same semantics as a = a + b and not a.MutateWith(b). If there isn't an assignment to a at the end then compound assignment is the wrong operator.

More generally: never make cutesy operator overloads. Operator overloads are there so that you can make two complex numbers add to a third, not so that you can make an customer plus a jar of peanut butter equal a purchase order, or some such silliness.

like image 145
Eric Lippert Avatar answered Oct 13 '22 00:10

Eric Lippert