3

I'm trying to validate dynamic conditions. Is there a way to do:

string condition = "i == 3"; 

for (int i = 0; i < 5; i++) 
{ 
    if (condition)
    {
        // condition met
    }
}

or is this the wrong approach and there is a better way to dynamically evaluate a condition ?

hikizume
  • 578
  • 11
  • 25
  • 3
    What you want to do is called "eval". It is something normally considered to be **bad**. – xanatos Mar 18 '16 at 14:26
  • Possible reference: http://stackoverflow.com/questions/12556101/evaluate-conditional-expression, http://stackoverflow.com/q/6052640/613130 – xanatos Mar 18 '16 at 14:29
  • Use Roslyn to build a script engine http://www.jayway.com/2015/05/09/using-roslyn-to-build-a-simple-c-interactive-script-engine/ – Matthew Layton Mar 18 '16 at 14:54

1 Answers1

1

You can use a delegate expression like this, however this wouldnt convert a string to a expression. But maybe this is a approach that you should consider instead?

Func<int, bool> condition = i => i == 3;

for (int i = 0; i < 5; i++)
{
    if (condition(i))
    {
        Console.WriteLine(i);
    }
}
Simon Karlsson
  • 4,090
  • 22
  • 39
  • 1
    This is perfectly ok if there is a limited and pre-known number of possible conditions :-) – xanatos Mar 18 '16 at 14:30
  • It works fine with the example condition I mentioned (my mistake), but what happens when the condition goes a bit further (i % 3 == 0) ? – hikizume Mar 18 '16 at 14:44
  • 1
    That would work aswell, infact any expression that can be made on a `int` that results in a `bool` would work fine. And if you want to go further you could add more parameters to your delegate. – Simon Karlsson Mar 18 '16 at 14:45
  • @SimonKarlsson the string would not fit in the condition, as you mentioned in your answer. How can that last gap be bridged? what am I missing? – hikizume Mar 18 '16 at 14:57
  • @hikizume maybe you want to look into dynamic linq – Simon Karlsson Mar 18 '16 at 15:10