dynamicexpresso / DynamicExpresso

C# expressions interpreter

Home Page:http://dynamic-expresso.azurewebsites.net/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Checking if a variable exists

tinytownsoftware opened this issue · comments

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.

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);

Excellent, thank you very much.