Skip to content

Instantly share code, notes, and snippets.

Created November 3, 2011 00:02
Show Gist options
  • Save hartez/1335363 to your computer and use it in GitHub Desktop.
Save hartez/1335363 to your computer and use it in GitHub Desktop.
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