I came across this requirement where I needed to build a logical expression dynamically, then execute it and get the result for the same.
The basic challenge that I came across in doing so is that I received the expression in the form of a string something as the following:
- string expression ="true and false or true";
- //This returns a Compile Time error
- if(expression)
- {
- }
- //This gives a RunTime Error
- if(Convert.ToBoolean(expression))
- {
- }
- System.Data.DataTable table = new System.Data.DataTable();
- table.Columns.Add("", typeof(Boolean));
- table.Columns[0].Expression = expression;
- System.Data.DataRow r = table.NewRow();
- table.Rows.Add(r);
- bool blResult = (Boolean)r[0];
In the same way, we can also execute other operations that we receive as string.
For example, if we want to execute the expression : string expression = "3*(2+4)", then we can do the same in the following manner:
- DataTable dt = new DataTable();
- var v = dt.Compute("3 * (2+4)", "");
I hope it helped.

Anthony MoonsammyPosted May 19, 2023, 1:31 PM
How would “if (value1 == value2 && value3 || value4) {name = name3;}” be handled? Thank you
pooja guptaPosted Jul 19, 2015, 12:36 PM
woww, i didnt realize that such string "True and false or true" will give compile time error. Can you also explain why it usually give such error and wont work? because it is simply a string with 'and', 'or' operators. it should have worked. but it is not working. can you explain it. thanks