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 operato
You can use something like this:
class Program {
static void Main(string[] args) {
const int n = 5;
var a = new int[n] { 1, 2, 3, 4, 5 }.WithOperators();
var b = new int[n] { 5, 4, 3, 2, 1 };
int[] c = a + b;
for (int i = 0; i < c.Length; i++) {
Console.Write("{0} ", c[i]);
}
Console.WriteLine();
}
}
public static class Int32ArrayExtensions {
public static Int32ArrayWithOperators WithOperators(this int[] self) {
return self;
}
}
public class Int32ArrayWithOperators {
int[] _array;
public Int32ArrayWithOperators(int[] array) {
if (array == null) throw new ArgumentNullException("array");
_array = array;
}
public static implicit operator Int32ArrayWithOperators(int[] array) {
return new Int32ArrayWithOperators(array);
}
public static implicit operator int[](Int32ArrayWithOperators wrapper) {
return wrapper._array;
}
public static Int32ArrayWithOperators operator +(Int32ArrayWithOperators left, Int32ArrayWithOperators right) {
var x = left._array;
var y = right._array;
return x.Zip(y, (a, b) => a + b).ToArray();
}
}
Based on a related post that I wrote.