CSharp · Console
// C# Eval Expression
// Doc: https://eval-expression.net/eval-compile
// @nuget: Z.Expressions.Eval
/*
# How to use the Compile Method?
The `Compile` method allows you to compile any C# code or expression at runtime and return a delegate.
The `Compile` method offers the best performance when you need to execute the same expression multiple times but with different parameters:
The `Compile` method is slightly harder at first to understand than the [Execute](eval-execute) method. However, the `Compile` method offers the best performance as you directly use the delegate (compiled method).
See more: https://eval-expression.net/eval-compile
*/
using System;
using System.Collections.Generic;
using Z.Expressions;
public class Program
{
public static void Main()
{
var fizzBuzzCompiled = Eval.Compile<Func<int, string>>(@"
if (i % 15 == 0)
return $'{i} => FizzBuzz';
else if (i % 3 == 0)
return $'{i} => Fizz';
else if (i % 5 == 0)
return $'{i} => Buzz';
else
return $'{i} => {i}';
", "i");
var answers = new List<string>();
for(int i = 0; i <= 100; i++)
{
answers.Add(fizzBuzzCompiled(i));
}
Console.WriteLine(string.Join(Environment.NewLine, answers));
}
}