C# Eval - RegisterType / UnregisterType / IsRegisteredType Methods

CSharp · Console

/Program.cs

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

// @nuget: Z.Expressions.Eval

/*
## RegisterType

The RegisterType method registers all types provided. The method also register extension methods from types but doesn't registers other static member. For example, if you register the type "Z.MyNamespace.MyClass", you can now create an expression such as "new MyClass()" or any extension methods from this type.

In this example, we will register the type `MyClassHelper` and the type `MyExtensions` to register his extension methods. In the first expression, we will use our class and our extension methods with a simple arithmetic operation. Then we will demonstrate how to use the method `IsRegisteredType` and `UnregisterType` with our `MyClassHelper` to validate if the type is currently registered and to unregister it.

See more: https://eval-expression.net/register-unregister
*/

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

public class Program
{
	public static void Main()
	{
		// Global Context: EvalManager.DefaultContext.RegisterType(typeof(Helper));
		
		var context = new EvalContext();
		context.RegisterType(typeof(MyClassHelper));
		context.RegisterType(typeof(MyExtensions));
		
		var r1 = context.Execute<int>("new MyClassHelper().MyClassHelperID + 2.AddMe(3)"); // return 6
		Console.WriteLine("1 - Result: " + r1);
		
		// Check if the type `MyClassHelper` is registered
		var r2 = context.IsRegisteredType(typeof(MyClassHelper)); // return true
		Console.WriteLine("2 - Result: " + r2);
		
		// Unregister the type `MyClassHelper`
		context.UnregisterType(typeof(MyClassHelper));
		
		// Check the type `MyClassHelper` has been succesfully unregistered
		var r3 = context.IsRegisteredType(typeof(MyClassHelper)); // return false
		Console.WriteLine("3 - Result: " + r3);
	}
	
	public class MyClassHelper
	{
		public int MyClassHelperID { get; set; } = 1;
	}
}

public static class MyExtensions
{	
	public static int AddMe(this int x, int y)
	{
		return x + y;
	}
}
;