Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 :)

like image 918
VANDERWEYEN Jonathan Avatar asked May 13 '11 19:05

VANDERWEYEN Jonathan


People also ask

What are generic constraints?

The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function. Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type.

How do you add a generic constraint?

You can specify one or more constraints on the generic type using the where clause after the generic type name. The following example demonstrates a generic class with a constraint to reference types when instantiating the generic class.

Can generic classes be constrained?

You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter. The code below constrains a class to an interface.

What keyword allows you to put constraints on a generic type?

So here is the list of some of the constraints that you can add to the generic classes, using the where keyword: Restrict the generic class to use the type parameter of value or reference type only (as we discussed above). Restrict the type parameter T, to be implementing the specified interface.


1 Answers

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

  • in C# 4.0 and .NET 4.0 (or above), use dynamic, which supports + but offers no compile time checking
  • in .NET 3.5 (or above), MiscUtil offers an Operator class which makes operators available as methods - again, without any compile-time checking

So either:

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

or

return Operator.Add(left.Evaluate(context), right.Evaluate(context)); 
like image 93
Marc Gravell Avatar answered Sep 21 '22 18:09

Marc Gravell