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 :)
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.
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.
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.
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.
There are no such devices in C#. A few options are available, though:
dynamic
, which supports +
but offers no compile time checkingOperator
class which makes operators available as methods - again, without any compile-time checkingSo either:
return (dynamic)left.Evaluate(context) + (dynamic)right.Evaluate(context);
or
return Operator.Add(left.Evaluate(context), right.Evaluate(context));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With