Checking if a variable exists
tinytownsoftware opened this issue · comments
Tiny Town Software commented
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.
Christophe PLAT commented
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);
Tiny Town Software commented
Excellent, thank you very much.