What exactly (under the hood) do the +=
and -=
operators do?
Or are they implicit in that they are defined per type?
I've used them extensively, it's a very simple feature of the syntax, but I've never thought about the depths of how it works.
What Brought About the Question
I can concatenate a string value like so:
var myString = "hello ";
myString += "world";
All fine. But why doesn't this work with collections?
var myCol = new List<string>();
myCol += "hi";
You may say 'well you're attempting to append a different type, you can't append a string to a type that isn't string'. But the following doesn't work either:
var myCol = new List<string>();
myCol += new List<string>() { "hi" };
Ok, maybe it doesn't work with collections, but is the following not a (kind of) collection of event handlers?
myButton.Click += myButton_Click;
I'm obviously lacking an in-depth understanding of how these operators work.
Please note: I'm not trying to build the collection myCol
in this way, in a real project. I'm merely curious about the workings of this operator, it's hypothetical.
+=
does is easy, the in depth understand of why we wrote it to work that way is a bit more time consuming."10" + "20"
-"1020"
? Or"30"
? Who is to tell someone that there's a right or wrong way to answer that?+
is used to mean normal numeric addition, string concatenation, and sequencing of multicast delegates, and all three of these operations are only tangentially related to each other. It's a bit of an abuse of the intuition we all have about addition, and this leads to confusion. Your best bet is to think of+
and+=
as being several different things that have the same syntax for historical reasons."10" + "20"
is"1020"
as they are strings.10 + 20
is30
as they are numbers. isn't that obvious (in a staticly typed language)?