C# Eval - Execute Method - Simple Math Expression

CSharp · Console

/Program.cs

// C# Eval Expression
// Doc: https://eval-expression.net/eval-execute

// @nuget: Z.Expressions.Eval

/*
# How to use the Execute Method?

The `Execute` method allows you to execute any C# code or expression at runtime.

It could be from a very simple math expression from an user input: https://dotnetfiddle.net/Jf9LMp

To a more complex C# code, such as solving the famous [FizzBuzz](https://en.wikipedia.org/wiki/Fizz_buzz) interview question:  https://dotnetfiddle.net/BBJ4Ut

In short, the `Execute` method from the C# Eval Expression library let you execute any C# code at runtime that you usually write in Visual Studio.

See more: https://eval-expression.net/eval-execute
*/

using System;
using Z.Expressions;

public class Program
{
	public static void Main()
	{
		// Let's assume the user input is from someone that wants to solve a Facebook math problem
		var userInput = "6-1*0";

		// Execute the user input to solve the math expression
		var r = Eval.Execute<int>(userInput); // return 6

		// The answer is 6 due to multiply operator priority "6-1*0" => "6-(1*0)" => "6-0" => "6"
		Console.WriteLine("The result is: " + r);
	}
}

;