Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
126 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...