Is there a generic constraint I could use for the + operator?

VANDERWEYEN Jonathan picture VANDERWEYEN Jonathan · May 13, 2011 · Viewed 9.7k times · Source

is there some 'where' type contraints in can add to make the follwing code compile ?

public class Plus<T> : BinaryOperator<T> where T : ...
{
    public override T Evaluate(IContext<T> context)
    {
        return left.Evaluate(context) + right.Evaluate(context);
    }
}

Thanks :)

Answer

Marc Gravell picture Marc Gravell · May 13, 2011

There are no such devices in C#. A few options are available, though:

So either:

return (dynamic)left.Evaluate(context) + (dynamic)right.Evaluate(context);

or

return Operator.Add(left.Evaluate(context), right.Evaluate(context));