Skip to content

Instantly share code, notes, and snippets.

@B1Z0N
Last active September 3, 2021 23:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save B1Z0N/a2029186d9e3c8b960fa290a2f0863fe to your computer and use it in GitHub Desktop.
Save B1Z0N/a2029186d9e3c8b960fa290a2f0863fe to your computer and use it in GitHub Desktop.
using System.Linq.Expressions;
using System;
public static class Program
{
public static void Main()
{
Console.WriteLine(Program.ConstantOne<double>.Value);
Console.WriteLine(Program.ConstantOne<int>.Value);
// or any convertible type
}
public static class ConstantOne<TNum>
{
public static TNum Value { get; private set; }
static ConstantOne()
{
var integerConstant = Expression.Constant(1, typeof(int));
var genericTypeConstant = Expression.Convert(integerConstant, typeof(TNum));
var lambda = Expression.Lambda<Func<TNum>>(genericTypeConstant);
Value = lambda.Compile().Invoke();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment