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";
Now, if I try and execute it in any of the following manner, I received either a compile Time or a Run Time error ( I would leave it up to you guys to check it ).
or
-
- if(Convert.ToBoolean(expression))
- {
-
- }
Now, in order to get its output, we will use the following mentioned code:
- 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];
By doing this, we are creating a column of the type bool and then giving the expression as its values and while taking output of the same, we are again converting it to bool, it is here that the expression is executed and we get the desired output.
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)", "");
Doing so, we get the expected output i.e. 18 in the variable v.
I hope it helped.