What’s wrong with this C# code? I tried to overload the + operator to add two arrays, but got an error message as follows:
One of the parameters of a binary operator must be the containing type.
class Program
{
public static void Main(string[] args)
{
const int n = 5;
int[] a = new int[n] { 1, 2, 3, 4, 5 };
int[] b = new int[n] { 5, 4, 3, 2, 1 };
int[] c = new int[n];
// c = Add(a, b);
c = a + b;
for (int i = 0; i < c.Length; i++)
{
Console.Write("{0} ", c[i]);
}
Console.WriteLine();
}
public static int[] operator+(int[] x, int[] y)
// public static int[] Add(int[] x, int[] y)
{
int[] z = new int[x.Length];
for (int i = 0; i < x.Length; i++)
{
z[i] = x[i] + y[i];
}
return (z);
}
}
Operators must be declared inside a “related” class’ body. For instance:
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:
The will still lead to natural calls (
x.Add(y)) while avoiding to wrap arrays in your own class.