I want to use "*" or "\" as mathematical operators as such:
"I am going to clarify"
dim tbox as textbox
tbox.text = "*"
dim i as integer = 8 tbox.text 3
"End Clarify"
dim [mult] as string = "*"
dim [div] as string = "\"
dim i as integer = 8 [mult] 3
and the result would be i is equal to 24
or
dim i as integer = 8 [div] 2
and the result would be i is equal to 4
Can anyone solve this in one line without building a long, complex function? I would also like for this to be something that is already a part of the VB.NET structure and doesn't require an import.
If such a solution does not exist how do I do it with a function or .dll import?
Insert This into where you want to evaluate.
dim [mult] as string = "*"
dim [div] as string = "\"
'dim i as integer = 8 [mult] 3
op = mult
dim i As Integer = Eval("8" & op & "3")
'i is your result
Private Function Eval(ByVal command As String) As Object
Dim MyProvider As New VBCodeProvider 'Create a new VB Code Compiler
Dim cp As New CodeDom.Compiler.CompilerParameters 'Create a new Compiler parameter object.
cp.GenerateExecutable = False 'Don't create an object on disk
cp.GenerateInMemory = True 'But do create one in memory.
'If cp.OutputAssembly is used with a VBCodeProvider, it seems to want to read before it is executed.
'See C# CodeBank example for explanation of why it was used.
'the below is an empty VB.NET Project with a function that simply returns the value of our command parameter.
Dim ClassName As String = "class" & Now.Ticks
Dim TempModuleSource As String = "Imports System" & Environment.NewLine & _
"Namespace ns " & Environment.NewLine & _
" Public Class " & ClassName & Environment.NewLine & _
" Public Shared Function Evaluate()" & Environment.NewLine & _
" Return (" & command & ")" & Environment.NewLine & _
" End Function" & Environment.NewLine & _
" End Class" & Environment.NewLine & _
"End Namespace"
'Create a compiler output results object and compile the source code.
Dim cr As CodeDom.Compiler.CompilerResults = MyProvider.CompileAssemblyFromSource(cp, TempModuleSource)
If cr.Errors.Count > 0 Then
'If the expression passed is invalid or "", the compiler will generate errors.
'Throw New ArgumentOutOfRangeException("Invalid Expression - please use something VB could evaluate")
Return Nothing
Else
'Find our Evaluate method.
Dim methInfo As Reflection.MethodInfo = cr.CompiledAssembly.GetType("ns." & ClassName).GetMethod("Evaluate")
'Invoke it on nothing, so that we can get the return value
Return methInfo.Invoke(methInfo, New Object() {})
End If
End Function
You can use CodeDom to evaluate expressions. The expression in your example would be "8 * 3"
, or "8" + tbox.Text + "3"
.
Here's an example of how to do this in VB.NET. The function is certainly more than a one liner, but calling it will be simple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With