5

When declaring a binary operator, at least one of the operand types must be the containing type. This sounds a good design decision in general. However, I didn't expect the following code to cause this error:

public class Exp<T>
{
    public static Exp<int> operator +(Exp<int> first, Exp<int> second)
    {
        return null;
    }
}

What is the problem with this operator? Why this case falls into operator overloading restrictions of c#? is it dangerous to allow this kind of declaration?

nakhli
  • 4,009
  • 5
  • 38
  • 61

2 Answers2

5

Because the containing type is Exp<T>, not Exp<int>. What you are trying to do here is specialization a la C++, which is not possible in C#.

user703016
  • 37,307
  • 8
  • 87
  • 112
  • so the problem here is not that the operands are not related to containing types, which can be dangerous, but that it's not permitted to have "specializations"? – nakhli Jul 31 '11 at 20:03
  • Yes. What you are trying to do looks totally like C++ *template specialization* which is not directly possible in C#. Take a look at [this](http://stackoverflow.com/questions/600978/how-to-do-template-specialization-in-c). – user703016 Jul 31 '11 at 22:36
3

You are in a class of type Exp<T>, and neither of the parameters in the operator are Exp<T>, they're both Exp<int>.

Read this article for the suggested way around this.

Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142
  • I know that the types are different. In the case they are not related, I understand it can be dangerous. But here, it looks more like a limitation imposed by generics than a design safe-guard. Thank you for the suggested article! – nakhli Jul 31 '11 at 20:07