public
Created

Ridiculous operator overloading with expressions trees

  • Download Gist
gistfile1.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
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
 
Console.WriteLine(result);
Console.ReadLine();
}
}
 
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();
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.