Executing Dynamic Logical Expressions in C#

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: 

  1. 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 ).
  1. //This returns a Compile Time error   
  2. if(expression)   
  3. {   
  4. }  
or
  1. //This gives a RunTime Error   
  2. if(Convert.ToBoolean(expression))   
  3. {   
  4.   
  5. }   
Now, in order to get its output, we will use the following mentioned code:
  1. System.Data.DataTable table = new System.Data.DataTable();   
  2. table.Columns.Add(""typeof(Boolean));   
  3. table.Columns[0].Expression = expression;   
  4.   
  5. System.Data.DataRow r = table.NewRow();   
  6. table.Rows.Add(r);   
  7. 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:
  1. DataTable dt = new DataTable();   
  2. 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.

 

Next Recommended Reading C# Logical Questions with Answer