C# Eval - Compile Method - The code

CSharp · Console

/Program.cs

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

// @nuget: Z.Expressions.Eval

/*
### The code

This part is exactly like the [Execute Method](/eval-execute#the-code).

You can provide the code to compile in 3 different ways:

1. **Instance method:** `context.Compile(code)`
2. **Static method:** `Eval.Compile(code)`
3. **Extension method:** `"code".Compile`

1 - In the case of the **instance method** (`context.Compile(code)`). First, you create a new instance of the [EvalContext](/eval-context), and then you can use the `Compile` method from the context created:

2 - In the case of the **static method** (`Eval.Compile(code)`), you can directly call the static `Eval.Compile` method, which uses a global context under the hood: 

3 - In the case of the **extension method** (`"code".Compile`), you can directly call the `Compile` method that extends the string type, which uses a global context under the hood:

One of the major differences is whether you want to create a new instance of the [EvalContext](https://eval-expression.net/eval-context) or use the global context (an instance stored in a static variable).

We explain the answer more detail in the [EvalContext](https://eval-expression.net/eval-context) documentation, but in short:

- If you need to customize the context for this specific compilation, **you should** use an instance context
- If you don't need to customize the context for this specific compilation, **you can** use the global context

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

using System;
using System.Collections.Generic;
using Z.Expressions;

public class Program
{
	public static void Main()
	{
		// 1. **Instance method:** `context.Compile(code)`
		{
			// CREATE a new instance of EvalContext
			var context = new EvalContext();

			// USE the `Compile` method from the context created
			var compiledList1 = context.Compile<Func<List<int>>>("new List<int>() { 1, 2, 3 };");
			
			var list1 = compiledList1();

			FiddleHelper.WriteTable(list1);
		}
		
		// 2. **Static method:** `Eval.Compile(code)`
		{					
			// CALL the static `Eval.Compile` method
			var compiledList2 = Eval.Compile<Func<List<int>>>("new List<int>() { 1, 2, 3 };");
			
			var list2 = compiledList2();
			
			FiddleHelper.WriteTable(list2);
		}

		// 3. **Extension method:** `"code".Compile`
		{
			// CALL the `Compile` method that extends the string type
			var compiledList3 = "new List<int>() { 1, 2, 3 };".Compile<Func<List<int>>>();
			
			var list3 = compiledList3();
			
			FiddleHelper.WriteTable(list3);
		}
	}
}

;