SoFunction
Updated on 2025-03-06

C# Method steps to execute Javascript scripts

A while ago, I used C# to write a SCXML state machine and needed to parse EMCScript expressions, using Jint library (/sebastienros/jint/), I felt that the data conversion with C# was not very convenient at that time. I have been paying attention to it in the past two days and found that the new 3.0 version has been greatly improved. I will introduce it to you here for reference.

First, you need to install the nuget package. Pay attention to adding the prerelease option to install the latest version. Use the dotnet command line instructions as follows:

dotnet add  package Jint --prerelease

Directly compute expressions:

("Directly compute expression: (1+2)*3");
var r1= ("(1+2)*3");
(r1);

String operation:

("String operation: 'abc'.length");
var r2=("'abc'.length");
(r2);

("-----------------------");
("String operation:'abc'.substr(2)");
var r3=("'abc'.substr(2)");
(r3);

You can use SetValue to assign values ​​to JS variables:

var e2 = new Engine()
    .SetValue("x", 1)
    .SetValue("y",2);
var r4=("x+y");
(r4);

You can use objects to exchange data between C# and JS:

var myobj= new Student {
    Name="Zhang San"
};
();
var e4 = new Engine()
    .SetValue("student", myobj)
    .Execute(" = 'Li Si'");
();

You can delegate C# functions to the JS engine and call these functions in the JS code:

("Set the CSharp function to the Js engine");
var engine = new Engine()
    .SetValue("log", new Action<object>());
 (@"
    function hello() { 
        log('Hello World');
    };
 
    hello();
");

You can also call JS functions from CSharp:

("Calling BMI by calling JS functions");
var e5=new Engine()
    .Execute("function bmi(weight, height) { return weight/height/height; }");
(("bmi",75,1.75));

CLI can be introduced to call functions in the CLI in the JS engine:

("Calling .Net function to write to file");
var e6 = new Engine(cfg => ());
(@"var f=('');
        ('Hello !');
        ();");

Examples can be downloaded from github:/zhenl/CSharpScriptDemo, This article is an example in the JSInCSharp project.

This is the article about the methods and steps of executing Javascript scripts in C#. For more related content on executing Javascript scripts in C#, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!