dynamicexpresso / DynamicExpresso

C# expressions interpreter
http://dynamic-expresso.azurewebsites.net/
MIT License
1.98k stars 371 forks source link

Checking if a variable exists #240

Closed tinytownsoftware closed 2 years ago

tinytownsoftware commented 2 years ago

Is there a way to check if a variable exists from within an expression? We want to have the following expression:

VariableExists(IsMarried) ? (IsMarried ? "Yes" : "No") : "N/A"

The problem is, our variables are always dynamic from the database. So we don't know if IsMarried will be there, so we can't write an expression, otherwise it will throw If the variable is not set.

metoule commented 2 years ago

It's possible, but not within the expression, via the DetectIdentifiers method, which can detect all the unknown variables:

var expr = "IsMarried.HasValue ? IsMarried.Value ? \"Yes\" : \"No\" : \"N/A\"";

var target = new Interpreter();
var unknownIdentifiers = target.DetectIdentifiers(expr).UnknownIdentifiers;

You can then add a default value before evaluating the expression:

foreach (var name in unknownIdentifiers)
{
   target.SetVariable(name, null, typeof(bool?));
}

var result = target.Eval(expr);
tinytownsoftware commented 2 years ago

Excellent, thank you very much.