A useful feature in Visual Basic 6 and Office/VBA is the Eval() function. Eval evaluates the supplied string and return a
result. This offers the ability to evaluate arbitrary statements at runtime. Unfortunately, neither C# nor Visual Basic .NET has an equivalent feature.
Fortunately, .NET can call components authored in other .NET languages to make this fairly simple to implement.
to get to that function from our C# or Visual Basic .NET projects. To build your own Eval equivalent, follow these steps.
Step 1: Create a JScript Wrapper DLL
- Open Notepad and type in the following code:
function Evaluate(evalString : String)
- Save the file as jScriptEval.js and close NotePad.
command line shows how to do this. Typically, it is something like:
C:\WINDOWS\Microsoft.NET\Framework\ver\jsc.exe /t:library jScriptEval.js
where "ver" is your .NET Framework version to the directory where the compiler is installed.
- If everything worked, your directory should contain a file named jScriptEval.dll.
Step 2: Create References in your Visual Studio .NET project
- Back in your Visual Basic.NET or C# project, create a reference to your new DLL. To do this, right-click on your project, in the Solution Explorer,
Select the .NET tab, press the Browse button to locate JScriptEval.DLL and press [OK]
- You also need a reference to the Microsoft JScript library. This is
typically located in c:\windows\microsoft.net\framework\ver\Microsoft.JScipt.dll, where "ver" is your .NET Framework version.
Step 3: Test your new EVAL code
Test your EVAL library like this:
Dim j As New JScriptEval
Dim s1 As String = "1 + 2 * 3"
You should be aware that using Eval statements can lead to potential
security risks. Eval can execute just about any program code. There are two
ways to minimize this. First, you can use a regular expression evaluator to
make sure that the string passed to Eval contains only letters, operators
and numbers, not words. Secondly, consider using .NET security features to
disallow any potentially dangerous operations before code is executed by
Return to the Visual Studio
.NET tips page