1

I am generating a expression from some business rules and it might look like this

0 > 1
12 < 14
"abc" != "xyz"
90 >= 12

Now I have to do certain implementations based on that condition. For example:

 string condition = "0 =1";
 if(condition)
 {
  // do something because condition is passed
 }
else
 { 
  // do something because condition is failed
 }

I have tried to do the same with the dynamic keyword but it is still not working. Any work around?

Edit : 1 modified code

string _initExp = "1";
string _validateCondition = "== 0";
string strcondition = _initExp + _validateCondition;
bool _condition = Convert.ToBoolean(strcondition); // Error statement

if (_condition)
{

}
Zerotoinfinity
  • 6,290
  • 32
  • 130
  • 206
  • For this your best bet would probably be using the recently release [`Roslyn C# compiler`](http://roslyn.codeplex.com/). That will allow you to parse and execute any piece of C# code as strings. – Erik Schierboom May 22 '14 at 13:03
  • `strcondition` should be a `boolean value in string form`. – Bharadwaj May 22 '14 at 13:13
  • Read this: http://msdn.microsoft.com/en-us/library/86hw82a3(v=vs.110).aspx - as examples show you can't convert string `1 == 0` to `bool` value. – rosko May 22 '14 at 13:30
  • @Zerotoinfinite Try this, http://social.msdn.microsoft.com/Forums/vstudio/en-US/e28e3e87-64c8-4c0e-b4a4-4513978bece5/how-to-execute-c-statment-in-a-string#81b2d976-1836-40cf-ae65-1dc158765210 – Bharadwaj May 22 '14 at 13:35

1 Answers1

4

Why not just use bool:

bool condition = 0==1;
if(condition)
{
   // do something because condition is passed
}
else
{ 
   // do something because condition is failed
}

You can also simplify the following code:

bool condition = 0==1;
if(condition)
{
   return true;
}
else
{ 
   return false;
}

to:

bool condition = 0==1;
return condition;

Or for custom return values

bool condition = 0==1;
return condition ? "yes" : "no";
sshashank124
  • 31,495
  • 9
  • 67
  • 76