Overloading the + operator to add two arrays

Operators must be declared inside a “related” class’ body. For instance:

public class Foo
{
    int X;

    // Legal
    public static int operator+(int x, Foo y);

    // This is not
    public static int operator+(int x, int y);
}

Since you don’t have access to the implementation of arrays, your best bet would be to either wrap your arrays in your own implementation so you can provide additional operations (and this is the only way to make the operator+ work.

On the other hand, you could define an extension method like:

public static class ArrayHelper
{
    public static int[] Add(this int[] x, int[] y) { ... }
}

The will still lead to natural calls (x.Add(y)) while avoiding to wrap arrays in your own class.

Leave a Comment