Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
Ridiculous operator overloading with expressions trees
internal class Program
private static void Main(string[] args)
var x = new Number<int>(3);
var y = new Number<int>(-4);
Number<int> result = x + y; // result is 7
public class Number<T>
public Number(T value)
Value = value;
public T Value { get; set; }
public override string ToString()
return Value.ToString();
public static Number<T> operator +(Number<T> c1, Number<T> c2)
Func<T, T, T> func = a_plus_abs_b();
return new Number<T>(func(c1.Value, c2.Value));
public static Func<T, T, T> a_plus_abs_b()
ParameterExpression a = Expression.Parameter(typeof (int), "a");
ParameterExpression b = Expression.Parameter(typeof (int), "b");
BinaryExpression greaterThanZero = Expression.MakeBinary(ExpressionType.GreaterThan, b, Expression.Constant(0));
ConditionalExpression maths = Expression.Condition(greaterThanZero,
Expression.MakeBinary(ExpressionType.Add, a, b),
Expression.MakeBinary(ExpressionType.Subtract, a, b));
return Expression.Lambda<Func<T, T, T>>(maths, a, b).Compile();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.