-1

What would be the proper way to perform a mathematical calculation when the operator is a variable character. In other words, the operation is not known at compile-time. The operation needs to be dynamically chosen at run-time.

For instance, let's say I need to calculate the sum of 20 + 40, but the + operator is stored in a Char variable, like this:

Dim operator As Char = "+"c    
Dim result As Long = 10 operator 20
Steven Doggart
  • 43,358
  • 8
  • 68
  • 105
XK8ER
  • 770
  • 1
  • 10
  • 25

1 Answers1

2

The simple way would be to use a Select Case statement to perform the calculation using the correct operation based on the input character. For instance:

' Binary, as in not unary nor ternary
Public Function PerformBinaryOperation(operand1 As Long, operator As Char, operand2 As Long)
    Select Case operator
        Case "+"c
            Return operand2 + operand2
        Case "-"c
            Return operand2 - operand2
        ' ...
    End Select
End Function

The more advanced solution is to write an expression parser to analyze an expression string, such as "10 + 20", and turns it into an expression tree. If you don't want to go through the trouble of writing your own parser, you could use one of the available libraries to do it, such as NCalc.

Another alternative to expression tree parsing is to generate a snippet of .NET code, and then dynamically build and execute that code at run-time. For instance, if you did something like this:

Dim operator As Char = "+"c
Dim codeBuilder As New StringBuilder()
codeBuilder.AppendLine("Public Class MyOperation")
codeBuilder.AppendLine("    Public Function Calculate() As Long")
codeBuilder.AppendLine("         Return 10 " & operator & " 20")
codeBuilder.AppendLine("    End Function")
codeBuilder.AppendLine("End Class")
Dim myOperation As Object = ' ... compile code and instantiate object dynamically
Dim result As Long = myOperation.Calculate()

Traditionally, you would do that using the CodeDom classes to perform the dynamic compilation, but now with the new Roslyn compiler in .NET 4.6, you can use the new Emit functionality. Here is an article that introduces the various dynamic compilation options.

Steven Doggart
  • 43,358
  • 8
  • 68
  • 105