Generally, if you want to evaluate C# code during runtime, you can use
the .NET Compiler Platform (Roslyn) via the Microsoft.CodeAnalysis.CSharp.Scripting
Nuget package.
BTW, I found this right here in stack overflow: How can I evaluate a C# expression dynamically?
here's a solution to your specific requirement, assuming the only exception to valid C# expressions is treating !8 as boolean true (specifically "!8" preceded or followed followed by any other character is forbidden).
private async Task<bool> ProcessExpression(string expression)
{
var processedExpression = expression.Replace("!8", "true");
return await CSharpScript.EvaluateAsync<bool>(processedExpression);
}
And here's some test code for the above:
Task.Run(async () =>
{
var expresion = "8 > 9";
var result = await ProcessExpression(expresion);
Console.WriteLine($"{expresion} : {result}");
expresion = "8 < 9";
result = await ProcessExpression(expresion);
Console.WriteLine($"{expresion} : {result}");
expresion = "!8";
result = await ProcessExpression(expresion);
Console.WriteLine($"{expresion} : {result}");
expresion = "8 > 9 || !8";
result = await ProcessExpression(expresion);
Console.WriteLine($"{expresion} : {result}");
expresion = "8 > 9 && !8";
result = await ProcessExpression(expresion);
Console.WriteLine($"{expresion} : {result}");
});
The output we get is:
8 > 9 : False
8 < 9 : True
!8 : True
8 > 9 || !8 : True
8 > 9 && !8 : False
please note that this solution has a performance penalty and if this is a concert than you should look for other options such as writing a dedicated parser or look for 3rd party Nuget packages.