Search code examples
visual-studioexpressionevaluationreduction

Performing expression evaluation/reduction in Visual Studio 2008


Is it possible to get Visual Studio to do mathematical expression evaluation/reduction?

For example if I type '-0.005 + -0.345' how do I get Visual Studio to reduce that (i.e. replace it with the reduction)? Do I have to write a macro? If so, are there any pre-existing macros to do this type of expression reduction?

Just to be clear, I want to be able to highlight an expression and have it replaced with the reduced result. Many are suggesting the immediate window but I fail to see how that will suffice?

Edit I should point out that this is while editing not running or debugging. The immediate window is of little to no use. I also consider this a language neutral question. I would certainly be interested in seeing alternative macros to the one I had posted.

Edit Going Once... Going Twice... (i.e. any other suggestions before I consider accepting my own answer?)


Solution

  • Thank you for the above answers.

    There probably are better ways, but here's a quick and dirty macro that does what I need.

    References to the System.Data and System.XML namespaces need to be added.

    Highlight the expression you want to evaluate and run the macro (it uses the calculated column in the DataTable to evaluate the expression.) It will replace the expression with the reduced result.

    Edit - Updated code below. It worked extremely well for reducing a large number of expressions. As pointed out by others there is the immediate window but this will not work for editing purposes. This macro is a language independent solution for basic expressions "(), +, -, *, /".

    
    Sub Eval()
      Dim ts As EnvDTE.TextSelection = DTE.ActiveDocument.Selection
      Using dt As New DataTable()
        dt.Columns.Add("Expression", GetType(Double), ts.Text)
        dt.Rows.Add(dt.NewRow)
        ts.Text = CDbl(dt.Rows(0).Item("Expression"))
      End Using
    End Sub