You can do it with "little magic" from LINQ:
private static readonly Func adder;
static NumberContainer() {
var p1 = Expression.Parameter(typeof (T));
var p2 = Expression.Parameter(typeof (T));
adder = (Func)Expression
.Lambda(Expression.Add(p1, p2), p1, p2)
.Compile();
}
public T Total { get { return adder(ValueA, ValueB); } }
The only drawback is that this code will compile even if NumberContainer
is instantiated with a type T
that does not support addition; of course it will throw an exception at run-time. An added benefit is that this should work with user-defined +
operators.