[Mono-dev] Operator overloading in C#

Brian Crowell mono-devel at fluggo.com
Wed Mar 29 17:41:54 EST 2006

Rusmin Susanto wrote:
> If I need to access the operator quite often, I am afraid that a 
> numerous calls to "new" will slow down the program (as it needs to 
> allocate 200 x 200 array of double).

You're asking if, in A + B + C + D + E + F, only one new allocation can be made, 
is that correct? If so, then I'm afraid that just doesn't match the correct 
behavior of a operator +(). When you create an operator +(), it *must* return a 
new instance to satisfy the requirements of that operator. And really, you 
should be doing that regardless of the language.

What you're really trying to do is something more along the lines of:

M = A;
M += B;
M += C;

...which in C++ could be optimized to perform only the one allocation for M. C# 
does not work this way, as you cannot overload the += operator (except by 
overloading +), so the allocations would still be performed in this case.

A better solution is to create an Add() method on your class, which would add 
the argument's contents directly into your array, avoiding allocations altogether:

   public void Add( Foo value ) {
       for( int i = 0; i < __maxX; i++ )
           for( int j = 0; j < __maxY; j++ )
               _array[i,j] += value._array[i,j];

So your statement set then becomes:

   M = A;
   M.Add( B );
   M.Add( C );

This makes the actual behavior of the code more obvious.

To round out this pattern, you should also implement:

   public static Foo Add( Foo value1, Foo value2 ) {
       Foo result = new Foo();

       for( int i = 0; i < __maxX; i++ )
           for( int j = 0; j < __maxY; j++ )
               result._array[i,j] = value1._array[i,j] + value2._array[i,j];

       return result;

   public static Foo operator+( Foo value1, Foo value2 ) {
       return Add( value1, value2 );


More information about the Mono-devel-list mailing list