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.