Scripting API Samples
Scripting API Samples
Tomáš Matoušek edited this page on Jan 31 · 32 revisions
Pages 43
Performance considerations for large solutions
Other documentation in the repo
Contributors
Building, Testing, and Debugging
Tool Authors
Status
Edit-and-Continue Supported Edits
.NET Core
Interactive and Scripting
Interactive Window Documentation
Clone this wiki locally
The scripting APIs enable .NET applications to instatiate a C# engine and execute code snippets against host-supplied objects. Below are examples of how to get started with the scripting APIs and some common samples. You can also view the Scripting API source code.
Supported Platforms
Scripting APIs require desktop .NET Framework 4.6+, or .NET Core 1.1 (supported since Roslyn v2.0.0-rc3, Visual Studio 2017 RC3).
Scripting APIs can't be used within Universal Windows Applications and .NET Native since the application model doesn't support loading code generated at runtime.
Getting Started
Install the Scripting API NuGet Package:
Install-Package Microsoft.CodeAnalysis.CSharp.Scripting
Code Samples
Note: the samples require the following using:
using Microsoft.CodeAnalysis.CSharp.Scripting;Scenarios
- Evaluate a C# expression
- Evaluate a C# expression (strongly-typed)
- Evaluated a C# expression with error handling
- Add references
- Add imports
- Parameterize a script
- Create & build a C# script and execute it multiple times
- Create a delegate to a script
- Run a C# snippet and inspect defined script variables
- Chain code snippets to form a script
- Continue script execution from a previous state
- Create and analyze a C# script
- Customize assembly loading
object result = await CSharpScript.EvaluateAsync("1 + 2");
Evaluate a C# expression (strongly-typed)
int result = await CSharpScript.EvaluateAsync<int>("1 + 2");
Evaluate a C# expression with error handling
Console.WriteLine(await CSharpScript.EvaluateAsync("2+2"));
catch (CompilationErrorException e)
Console.WriteLine(string.Join(Environment.NewLine, e.Diagnostics));
var result = await CSharpScript.EvaluateAsync("System.Net.Dns.GetHostName()",
ScriptOptions.Default.WithReferences(typeof(System.Net.Dns).Assembly));
var result = await CSharpScript.EvaluateAsync("Sqrt(2)",
ScriptOptions.Default.WithImports("System.Math"));
var globals = new Globals { X = 1, Y = 2 };
Console.WriteLine(await CSharpScript.EvaluateAsync<int>("X+Y", globals: globals));
Note: Currently the Globals type has to be defined in an assembly loaded from a file. If the assembly is in-memory (including e.g. when the sample is executed in Interactive Window) the script won't be able to access the type. See issue here.
Create & build a C# script and execute it multiple times
var script = CSharpScript.Create<int>("X*Y", globalsType: typeof(Globals));
Console.WriteLine((await script.RunAsync(new Globals { X = i, Y = i })).ReturnValue);
The delegate doesn't hold compilation resources (syntax trees, etc.) alive.
var script = CSharpScript.Create<int>("X*Y", globalsType: typeof(Globals));
ScriptRunner<int> runner = script.CreateDelegate();
Console.WriteLine(await runner(new Globals { X = i, Y = i }));
Run a C# snippet and inspect defined script variables
var state = await CSharpScript.RunAsync<int>("int answer = 42;");
foreach (var variable in state.Variables)
Console.WriteLine($"{variable.Name} = {variable.Value} of type {variable.Type}");
Chain code snippets to form a script
Console.WriteLine((await script.RunAsync()).ReturnValue);
Continue script execution from a previous state
var state = await CSharpScript.RunAsync("int x = 1;");
state = await state.ContinueWithAsync("int y = 2;");
state = await state.ContinueWithAsync("x+y");
Console.WriteLine(state.ReturnValue);
Create and analyze a C# script
var script = CSharpScript.Create<int>("3");
Compilation compilation = script.GetCompilation();
Compilation gives access to the full set of Roslyn APIs.
using Microsoft.CodeAnalysis.Scripting.Hosting;
using (var loader = new InteractiveAssemblyLoader())
var script = CSharpScript.Create<int>("1", assemblyLoader: loader);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2005-07-01 期末小结(三).我是玻璃缸里的鱼
2005-07-01 期末小结(一). 专业技术