Generics and "One of the parameters of a binary operator must be an addition type" Error

When declaring a binary operator, there must be at least one of the operand types. This sounds like a good design decision overall. However, I did not 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 does this case fall into C # operator overloading? Is it dangerous to allow such a declaration?

+4
source share
2 answers

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

+5
source

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

Read this article for a suggested path around this.

+3
source

All Articles