Last active
September 3, 2021 23:33
-
-
Save B1Z0N/a2029186d9e3c8b960fa290a2f0863fe to your computer and use it in GitHub Desktop.
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
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