132

I am trying to do operator overloads for +=, but I can't. I can only make an operator overload for +.

How come?

Edit

The reason this is not working is that I have a Vector class (with an X and Y field). Consider the following example.

vector1 += vector2;

If my operator overload is set to:

public static Vector operator +(Vector left, Vector right)
{
    return new Vector(right.x + left.x, right.y + left.y);
}

Then the result won't be added to vector1, but instead, vector1 will become a brand new Vector by reference as well.

7
  • 2
    Looks like a long discussion has already been had about this: maurits.wordpress.com/2006/11/27/…
    – Chris S
    Jul 5, 2011 at 18:26
  • 39
    Can you explain why you're trying to do this? You get an overloaded "+=" operator for free when you overload "+". Is there some situation in which you do want "+=" to be overloaded but do not want "+" to be overloaded? Jul 5, 2011 at 18:27
  • 3
    Coming from C++, this just feels wrong, but in C# it actually makes perfect sense.
    – Jon Purdy
    Jul 6, 2011 at 3:41
  • 2
    possible duplicate of Why cant i overload the += operator in C#? But i still can use it?
    – benzado
    Jul 6, 2011 at 16:34
  • 13
    @Mathias: re your update: Vectors should behave like immutable mathematical objects. When you add 2 to 3, you don't mutate the object 3 into the object 5. You create an entirely new object, 5. The point of overloading addition operators is to make your own mathematical objects; making them mutable works against that aim. I would make your vector type an immutable value type. Jul 7, 2011 at 22:43

10 Answers 10

161

Overloadable Operators, from MSDN:

Assignment operators cannot be overloaded, but +=, for example, is evaluated using +, which can be overloaded.

Even more, none of assignment operators can be overloaded. I think this is because there will be an effect for the Garbage collection and memory management, which is a potential security hole in CLR strong typed world.

Nevertheless, let's see what exactly an operator is. According to the famous Jeffrey Richter's book, each programming language has its own operators list, which are compiled in a special method calls, and CLR itself doesn't know anything about operators. So let's see what exactly stays behind the + and += operators.

See this simple code:

Decimal d = 10M;
d = d + 10M;
Console.WriteLine(d);

Let view the IL-code for this instructions:

  IL_0000:  nop
  IL_0001:  ldc.i4.s   10
  IL_0003:  newobj     instance void [mscorlib]System.Decimal::.ctor(int32)
  IL_0008:  stloc.0
  IL_0009:  ldloc.0
  IL_000a:  ldc.i4.s   10
  IL_000c:  newobj     instance void [mscorlib]System.Decimal::.ctor(int32)
  IL_0011:  call       valuetype [mscorlib]System.Decimal [mscorlib]System.Decimal::op_Addition(valuetype [mscorlib]System.Decimal,
                                                                                                valuetype [mscorlib]System.Decimal)
  IL_0016:  stloc.0

Now lets see this code:

Decimal d1 = 10M;
d1 += 10M;
Console.WriteLine(d1);

And IL-code for this:

  IL_0000:  nop
  IL_0001:  ldc.i4.s   10
  IL_0003:  newobj     instance void [mscorlib]System.Decimal::.ctor(int32)
  IL_0008:  stloc.0
  IL_0009:  ldloc.0
  IL_000a:  ldc.i4.s   10
  IL_000c:  newobj     instance void [mscorlib]System.Decimal::.ctor(int32)
  IL_0011:  call       valuetype [mscorlib]System.Decimal [mscorlib]System.Decimal::op_Addition(valuetype [mscorlib]System.Decimal,
                                                                                                valuetype [mscorlib]System.Decimal)
  IL_0016:  stloc.0

They are equal! So the += operator is just syntactic sugar for your program in C#, and you can simply overload + operator.

For example:

class Foo
{
    private int c1;

    public Foo(int c11)
    {
        c1 = c11;
    }

    public static Foo operator +(Foo c1, Foo x)
    {
        return new Foo(c1.c1 + x.c1);
    }
}

static void Main(string[] args)
{
    Foo d1 =  new Foo (10);
    Foo d2 = new Foo(11);
    d2 += d1;
}

This code will be compiled and successfully run as:

  IL_0000:  nop
  IL_0001:  ldc.i4.s   10
  IL_0003:  newobj     instance void ConsoleApplication2.Program/Foo::.ctor(int32)
  IL_0008:  stloc.0
  IL_0009:  ldc.i4.s   11
  IL_000b:  newobj     instance void ConsoleApplication2.Program/Foo::.ctor(int32)
  IL_0010:  stloc.1
  IL_0011:  ldloc.1
  IL_0012:  ldloc.0
  IL_0013:  call       class ConsoleApplication2.Program/Foo ConsoleApplication2.Program/Foo::op_Addition(class ConsoleApplication2.Program/Foo,
                                                                                                          class ConsoleApplication2.Program/Foo)
  IL_0018:  stloc.1

Update:

According to your Update - as the @EricLippert says, you really should have the vectors as an immutable object. Result of adding of the two vectors is a new vector, not the first one with different sizes.

If, for some reason you need to change first vector, you can use this overload (but as for me, this is very strange behaviour):

public static Vector operator +(Vector left, Vector right)
{
    left.x += right.x;
    left.y += right.y;
    return left;
}
10
  • 2
    Stating that it's the case is not answering why. Jul 6, 2011 at 16:44
  • 1
    @Jouke van der Maas And how do you want me to answer why it is not possible? It is impossible by design, what else can I say?
    – VMAtm
    Jul 6, 2011 at 16:47
  • 2
    Why they designed it this way; that's what the question is, really. See some of the other answers. Jul 6, 2011 at 16:50
  • 2
    "Strange behavior" only if you have been "born" programming in C# :p. But, since the answer is correct and very well explained, you get my +1, as well ;)
    – ThunderGr
    Apr 8, 2014 at 10:12
  • 6
    @ThunderGr No, it's pretty strange no matter which language you're looking at. To make the statement v3 = v1 + v2; result in v1 being changed as well as v3 is unusual Jul 26, 2016 at 7:57
18

This is because of the same reason that the assignment operator cannot be overloaded. You cannot write code that would perform the assignment correctly.

class Foo
{
   // Won't compile.
   public static Foo operator= (Foo c1, int x)
   {
       // duh... what do I do here?  I can't change the reference of c1.
   }
}

Assignment operators cannot be overloaded, but +=, for example, is evaluated using +, which can be overloaded.

From MSDN.

18

You can't overload += because it isn't really a unique operator, it's just syntactic sugar. x += y is just a shorthand way of writing x = x + y. Because += is defined in terms of the + and = operators, allowing you to override it separately could create problems, in cases where x += y and x = x + y didn't behave in the exact same way.

At a lower level, it's very likely that the C# compiler compiles both expressions down to the same bytecode, meaning that it's very likely the the runtime can't treat them differently during program execution.

I can understand that you might want to treat it like a separate operation: in an statement like x += 10 you know that you can mutate the x object in place and perhaps save some time/memory, rather than creating a new object x + 10 before assigning it over the old reference.

But consider this code:

a = ...
b = a;
a += 10;

Should a == b at the end? For most types, no, a is 10 more than b. But if you could overload the += operator to mutate in place, then yes. Now consider that a and b could get passed around to distant parts of the program. Your possible optimization could create confusing bugs if your object starts to change where code doesn't expect it to.

In other words, if performance is that important, it's not too hard to replace x += 10 with a method call like x.increaseBy(10), and it's a lot clearer for everyone involved.

4
  • 2
    Personally, I would change it's just syntactic sugar to it's just syntactic sugar in C#; otherwise, it sounds too general, but in some programming languages, it is not just syntactic sugar but might actually give performance benefits. Jul 6, 2011 at 10:08
  • For simple (int, float, etc.) types, += could probably be optimized by a smart compiler, because arithmetic is simple. But once you're dealing with objects, all bets are off. Any language faces pretty much the same problems. This is why operator overloading is evil.
    – benzado
    Jul 6, 2011 at 16:32
  • @SebastianMach The question is specifically tagged with c# and dotnet tags. Obviously, in c++ for example, '+' and '+=' (and even '=') can be overloaded separately. Jul 16, 2020 at 12:10
  • 1
    @BojidarStanchev: True that. I apologize for my 9 years younger self :-D Jul 24, 2020 at 6:49
18

I think you'll find this link informative: Overloadable Operators

Assignment operators cannot be overloaded, but +=, for example, is evaluated using +, which can be overloaded.

1
  • 2
    @pickypg - this comment is not related to this thread: please undelete your answer, it does answer my question, I think I have no choice but to use your method, I thought there is some better way to solve it. Mar 9, 2012 at 2:01
9

This is because of this operator can't be overloaded:

Assignment operators cannot be overloaded, but +=, for example, is evaluated using +, which can be overloaded.

MSDN

Just overload + operator, because of

x += y equal to x = x + y

0
6

Operator overload for + is used in += operator, A += B equals to A = operator+(A, B).

6

If you overload + operator like this:

class Foo
{
    public static Foo operator + (Foo c1, int x)
    {
        // implementation
    }
}

you can do

 Foo foo = new Foo();
 foo += 10;

or

 foo = foo + 10;

This will compile and run equally.

6

There is always the same answer to this problem: Why do you need the +=, if you get it for free if you overload the +. But what happens if I have a class like this.

using System;
using System.IO;

public class Class1
{
    public class MappableObject
    {
        FileStream stream;

        public  int Blocks;
        public int BlockSize;

        public MappableObject(string FileName, int Blocks_in, int BlockSize_in)
        {
            Blocks = Blocks_in;
            BlockSize = BlockSize_in;

            // Just create the file here and set the size
            stream = new FileStream(FileName); // Here we need more params of course to create a file.
            stream.SetLength(sizeof(float) * Blocks * BlockSize);
        }

        public float[] GetBlock(int BlockNo)
        {
            long BlockPos = BlockNo * BlockSize;

            stream.Position = BlockPos;

            using (BinaryReader reader = new BinaryReader(stream))
            {
                float[] resData = new float[BlockSize];
                for (int i = 0; i < BlockSize; i++)
                {
                    // This line is stupid enough for accessing files a lot and the data is large
                    // Maybe someone has an idea to make this faster? I tried a lot and this is the simplest solution
                    // for illustration.
                    resData[i] = reader.ReadSingle();
                }
            }

            retuen resData;
        }

        public void SetBlock(int BlockNo, float[] data)
        {
            long BlockPos = BlockNo * BlockSize;

            stream.Position = BlockPos;

            using (BinaryWriter reader = new BinaryWriter(stream))
            {
                for (int i = 0; i < BlockSize; i++)
                {
                    // Also this line is stupid enough for accessing files a lot and the data is large
                    reader.Write(data[i];
                }
            }

            retuen resData;
        }

        // For adding two MappableObjects
        public static MappableObject operator +(MappableObject A, Mappableobject B)
        {
            // Of course we have to make sure that all dimensions are correct.

            MappableObject result = new MappableObject(Path.GetTempFileName(), A.Blocks, A.BlockSize);

            for (int i = 0; i < Blocks; i++)
            {
                float[] dataA = A.GetBlock(i);
                float[] dataB = B.GetBlock(i);

                float[] C = new float[dataA.Length];

                for (int j = 0; j < BlockSize; j++)
                {
                    C[j] = A[j] + B[j];
                }

                result.SetBlock(i, C);
            }
        }

        // For adding a single float to the whole data.
        public static MappableObject operator +(MappableObject A, float B)
        {
            // Of course we have to make sure that all dimensions are correct.

            MappableObject result = new MappableObject(Path.GetTempFileName(), A.Blocks, A.BlockSize);

            for (int i = 0; i < Blocks; i++)
            {
                float[] dataA = A.GetBlock(i);

                float[] C = new float[dataA.Length];

                for (int j = 0; j < BlockSize; j++)
                {
                    C[j] = A[j] + B;
                }

                result.SetBlock(i, C);
            }
        }

        // Of course this doesn't work, but maybe you can see the effect here.
        // when the += is automimplemented from the definition above I have to create another large
        // object which causes a loss of memory and also takes more time because of the operation -> altgough its
        // simple in the example, but in reality it's much more complex.
        public static MappableObject operator +=(MappableObject A, float B)
        {
            // Of course we have to make sure that all dimensions are correct.

            MappableObject result = new MappableObject(Path.GetTempFileName(), A.Blocks, A.BlockSize);

            for (int i = 0; i < Blocks; i++)
            {
                float[] dataA = A.GetBlock(i);

                for (int j = 0; j < BlockSize; j++)
                {
                    A[j]+= + B;
                }

                result.SetBlock(i, A);
            }
        }
    }
}

Do you still say that it is good that the += is "auto-implemented". If you try to do high-performance computing in C# you need to have such features to reduce processing time and memory consumption, if someone has a good solution it is highly appreciated, but don't tell me I have to do this with static methods, this is only a workaround and I see no reason why C# does the += implemention if it is not defined, and if it is defined it will be used. Some people say that not having a difference between + and += prevents errors, but isn't this my own problem?

4
  • 2
    If you really care about performance, you're not going to mess around with operator overloading, which only makes it harder to tell what code is being invoked. As for whether messing up the semantics of += is your own problem... that's only true if nobody else ever has to read, maintain, or execute your code.
    – benzado
    Jul 6, 2011 at 16:27
  • 2
    Hello, benzado. In some way you are right, but what we have is a platform for high-performance computing to create prototype applications. In one way we need to have the performance, on the other side we need a simple semantic. In fact we also like to have more operators than C# currently delivers. Here I'm hoping for C# 5 and the compiler as a service technique to get more out of the C# language. Nevertheless as I grew up with C++ and would appreciate if there are a little more features from C++ in C#, altough I would not like to touch C++ again since I#m doing C#.
    – msedi
    Jul 10, 2011 at 14:21
  • 2
    Engineering is all about tradeoffs; everything you want comes with a price.
    – benzado
    Jul 11, 2011 at 17:43
  • 3
    Arithmetic operators return new instances by convention - hence they are usually overridden on immutable types. You can't add a new element to a List<T> using an operator like list += "new item", for example. You call its Add method instead. Dec 22, 2016 at 12:17
3

I had the exact same question and i can not possibly answer it better then this person has

-1

A better design method is Explicit Casting. You can definitely overload Casting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.