Why didn't Microsoft overload the + = operator for the line editor?

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

Append () only concatenates strings, so why don't they just overload the + = operator as follows:

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

Is this an example of efficiency? Is this a case of convention or intuition?

Thanks,

+7
c #
source share
1 answer

Arithmetic operations must be limited to types that act as arithmetic values. It is bad enough that the sum of two lines is the third line. Merging the add operation with string concatenation is a dubious choice, since string concatenation obeys very few add rules; in particular, a + b != b + a .

But going there for string collectors - which by definition are changing, rather than arithmetic values โ€‹โ€‹- is horrid . The sum of two things must be the third thing, which is different from the two terms. That is, a += b should have the same semantics as a = a + b , not a.MutateWith(b) . If at the end there is no binding to a , then the compound assignment is the wrong operator.

More generally: never overload operators \ . Operator overloads exist, so you can make two complex numbers an addition to the third one, and not that you can make a customer plus a can of peanut butter equal to a purchase order, or some such nonsense.

+27
source share

All Articles