How to evaluate (((2+5)*1000)/((30-12)*6)) at runtime in VB.net?

Rajnilari2015
Posted by Rajnilari2015 under VB.NET category on | Points: 40 | Views : 428
The below code will help to do so

Imports Microsoft.CSharp
Imports System.CodeDom.Compiler
Imports System.Data
Imports System.Reflection
Imports System.Text

Namespace ConsoleApplication5
Class Program
Private Shared Sub Main(args As String())
' object result = Eval("((10 + 12)*5)"); //result 110
Dim result As Object = Eval("(((2+5)*1000)/((30-12)*6))")
'result 64
End Sub

Private Shared Function Eval(sExpression As String) As Object
Dim c As New CSharpCodeProvider()
Dim cp As New CompilerParameters()

cp.ReferencedAssemblies.Add("system.dll")

cp.CompilerOptions = "/t:library"
cp.GenerateInMemory = True

Dim sb As New StringBuilder("")
sb.Append("using System;" & vbLf)

sb.Append("namespace CSCodeEvaler{ " & vbLf)
sb.Append("public class CSCodeEvaler{ " & vbLf)
sb.Append("public object EvalCode(){" & vbLf)
sb.Append((Convert.ToString("return ") & sExpression) + "; " & vbLf)
sb.Append("} " & vbLf)
sb.Append("} " & vbLf)
sb.Append("}" & vbLf)

Dim cr As CompilerResults = c.CompileAssemblyFromSource(cp, sb.ToString())
If cr.Errors.Count > 0 Then
Throw New InvalidExpressionException(String.Format("Error ({0}) evaluating: {1}", cr.Errors(0).ErrorText, sExpression))
End If

Dim a As Assembly = cr.CompiledAssembly
Dim o As Object = a.CreateInstance("CSCodeEvaler.CSCodeEvaler")

Dim t As Type = o.[GetType]()
Dim mi As MethodInfo = t.GetMethod("EvalCode")

Dim s As Object = mi.Invoke(o, Nothing)
Return s

End Function
End Class
End Namespace

Comments or Responses

Login to post response