How to Calculate a string math expression

• Question

• What I want is a method eg:

object calc(string exp)

It works like

int a=5

int b=6

calc("a+b*a") //should return 35

And this method also can calculate the bool value likes

bool a=true

bool b=false

int c=5

int d=4

calc("a&&b||(c>d)") //should return true

Wednesday, August 13, 2014 1:48 AM

Gaurav Khanna | Microsoft VB.NET MVP | Microsoft Community Contributor

Wednesday, August 13, 2014 1:15 PM
• Try these experiments too:

```{
DataTable dt = new DataTable();
dt.Columns.Add( "a", typeof( int ) );
dt.Columns.Add( "b", typeof( int ) );
dt.Columns.Add( "r", typeof( int ), "a + b * a" );
int result = (int)( dt.Rows[0]["r"] );
Console.WriteLine( result );
}
{
DataTable dt = new DataTable();
dt.Columns.Add( "a", typeof( bool ) );
dt.Columns.Add( "b", typeof( bool ) );
dt.Columns.Add( "c", typeof( int ) );
dt.Columns.Add( "d", typeof( int ) );
dt.Columns.Add( "r", typeof( bool ), "a AND b OR (c > d)" );
dt.Rows.Add( true, false, 5, 4 );
bool result = (bool)( dt.Rows[0]["r"] );
Console.WriteLine( result );
}
```

Thursday, August 14, 2014 5:38 AM

All replies

Gaurav Khanna | Microsoft VB.NET MVP | Microsoft Community Contributor

Wednesday, August 13, 2014 1:15 PM
• Try these experiments too:

```{
DataTable dt = new DataTable();
dt.Columns.Add( "a", typeof( int ) );
dt.Columns.Add( "b", typeof( int ) );
dt.Columns.Add( "r", typeof( int ), "a + b * a" );
int result = (int)( dt.Rows[0]["r"] );
Console.WriteLine( result );
}
{
DataTable dt = new DataTable();
dt.Columns.Add( "a", typeof( bool ) );
dt.Columns.Add( "b", typeof( bool ) );
dt.Columns.Add( "c", typeof( int ) );
dt.Columns.Add( "d", typeof( int ) );
dt.Columns.Add( "r", typeof( bool ), "a AND b OR (c > d)" );
dt.Rows.Add( true, false, 5, 4 );
bool result = (bool)( dt.Rows[0]["r"] );
Console.WriteLine( result );
}
```

Thursday, August 14, 2014 5:38 AM