Ridiculous operator overloading with expressions trees
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment