views:

607

answers:

4

I have some c# code that uses the Microsoft Scripting Control to evaluate some expressions:

using MSScriptControl; // references msscript.ocx

ScriptControlClass sc = new ScriptControlClass();
sc.Language = "VBScript";
sc.AllowUI = true;

try
{
    Console.WriteLine(sc.Eval(txtEx.Text).ToString());
}
    catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}

(txtEx is a simple text field)

Numerical expressions: "6+4", "cos(34)", "abs(-99)", "round(1.234, 2)" etc. are fine

Boolean expressions: "true or false", "1=2" are fine

But how can I evaluate a simple 'if'? I have tried "if(true, 2, 3)", "iif(true, 2, 3)", "if (true) then 2 else 3" and "if (true) then 2 else 3 endif"

Can anybody please help me to evaluate simple conditional expressions? Any help much appreciated!

RH

+1  A: 

You should consider using the expression evaluation engine that is part of Windows Workflow Foundation. Both the evaluator and the designer for it can be used separately from WF.

John Saunders
+3  A: 

Try wrapping your IF-expression in a function

Function test
   if (true) then
      return true
   else
      return false
   end if
End function

Add the function to the control and then use Run

Result = ScriptControl.Run("Test")

(the code above is not tested, but something along that way should work)

Check out this link for some more info

http://support.microsoft.com/kb/184740

Brummo
+1  A: 
if (true) then return 2 else return 3
Akash Kava
A: 

Thanks for the tips! After a bit more experimenting, based on Brummo's help, this seems to work:

txtEx contains this text:

function test
  if (1=1) then 
    test = true
  else 
    test = false
  end if
end function

then

sc.AddCode(txtEx.Text);

and

object[] myParams = { };
Console.WriteLine(sc.Run("Test", ref myParams).ToString());

This isn't ideal, since I really wanted to evaluate an expression, without building, loading and evaluating a function. (I am surprised IIF doesn't work for simple one line if evaluation).

Ryan
Beware of an IIF!
Anton Gogolev