Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 444
nakhli Avatar asked Jul 31 '11 19:07

nakhli


2 Answers

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#.

like image 75
user703016 Avatar answered Sep 28 '22 05:09

user703016


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.

like image 41
Yuriy Faktorovich Avatar answered Sep 28 '22 03:09

Yuriy Faktorovich