Skip to content

Instantly share code, notes, and snippets.

@ZacharyPatten
Last active December 11, 2019 16:18
Show Gist options
  • Save ZacharyPatten/40eb342ca6d5b6b037feb5d6538491fa to your computer and use it in GitHub Desktop.
Save ZacharyPatten/40eb342ca6d5b6b037feb5d6538491fa to your computer and use it in GitHub Desktop.
Generic Mathematics Example Using Runtime Compilation in C#
using System;
using System.Linq.Expressions;
using System.Numerics;
using static Towel.Syntax;
namespace Example
{
public class Program
{
static void Main(string[] args)
{
// This code is a snippet from the https://github.com/ZacharyPatten/Towel project.
// Please check out the project if you want to see more code like it. :)
int a = Addition(1, 2);
float b = Addition(1.2f, 3.4f);
double c = Addition(1.23d, 4.56d);
decimal d = Addition(1.234m, 5.678m);
BigInteger e = Addition(new BigInteger(12345), new BigInteger(67890));
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
Console.WriteLine(d);
Console.WriteLine(e);
}
}
}
namespace Towel
{
public static class Syntax
{
public static T Addition<T>(T a, T b)
{
return AdditionImplementation<T>.Function(a, b);
}
internal static class AdditionImplementation<T>
{
internal static Func<T, T, T> Function = (T a, T b) =>
{
ParameterExpression A = Expression.Parameter(typeof(T));
ParameterExpression B = Expression.Parameter(typeof(T));
Expression BODY = Expression.Add(A, B);
Function = Expression.Lambda<Func<T, T, T>>(BODY, A, B).Compile();
return Function(a, b);
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment