C# Interactive
suggest changeC# is a compiled language, but you don't need a project, a Main method and a build step to try out a line of code. There are several ways to run C# interactively, in a REPL (read-eval-print loop), or as a script:
| Tool | What it is | Runs on | NuGet packages |
|---|---|---|---|
csi.exe |
REPL and .csx runner shipped with Visual Studio |
.NET Framework 4.8 | no |
| C# Interactive window | csi inside Visual Studio |
.NET Framework or .NET | no |
dotnet-script |
REPL and .csx runner, a .NET global tool |
.NET 10 | #r "nuget: ..." |
csharprepl |
REPL with syntax highlighting and IntelliSense, a .NET global tool | .NET 10 | #r "nuget: ..." |
dotnet run app.cs |
file-based programs, built into the SDK | .NET 10 | #:package |
| Roslyn scripting API | embed a REPL in your own program | any | you decide |
All of them except file-based programs are built on the same Roslyn scripting engine (Microsoft.CodeAnalysis.CSharp.Scripting), so they share the same dialect of C#, described below.
Script dialect of C#
Interactive C# (also used in .csx files) is regular C# with a few changes:
- Statements, method declarations and type declarations can appear at the top level, in any order.
- An expression without a trailing semicolon is evaluated and its value is printed.
awaitworks at the top level.- Each submission can see the variables, methods and types declared by previous submissions. A variable can be re-declared with a new type.
namespacedeclarations aren't allowed.#radds a reference to an assembly (or a NuGet package indotnet-scriptandcsharprepl) and#loadruns another.csxfile.
Here's a session in csi, the C# Interactive compiler. It ships with Visual Studio and is available on PATH in the Developer Command Prompt or Developer PowerShell:
> csi
Microsoft (R) Visual C# Interactive Compiler version 5.9.0-1.26357.3 ()
Copyright (C) Microsoft Corporation. All rights reserved.
Type "#help" for more information.
> 1 + 2
3
> var names = new[] { "Ada", "Linus", "Grace" };
> names.Where(n => n.Length > 3)
Enumerable.WhereArrayIterator<string> { "Linus", "Grace" }
> int Square(int x) => x * x;
> Square(12)
144
> var x = 10;
> x * 2
20
> var x = "now a string";
> x.Length
12
> new Dictionary<string, int> { ["a"] = 1 }
Dictionary<string, int>(1) { { "a", 1 } }
> (1, "two")
(1, two)
> await Task.FromResult(42)
42
> "abc".Foo()
(1,7): error CS1061: 'string' does not contain a definition for 'Foo' and no accessible extension method 'Foo' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
> throw new InvalidOperationException("boom");
System.InvalidOperationException: boom
Notice the difference between var names = ...; (a statement, nothing printed) and names.Where(...) (an expression, its value printed). The REPL formats values in a readable way: collections show their element count and contents, strings are quoted.
Errors don't end the session. A submission that fails to compile is discarded and the state from earlier submissions is kept.
A submission can span several lines. When you press Enter on an incomplete statement, the REPL waits for more input (shown as .):
> for (int i = 0; i < 3; i++)
. {
. Console.Write(i);
. }
012
Type declarations work too, but because there are no namespaces they become nested classes of a generated submission class:
> namespace Foo { class A {} }
(1,1): error CS7021: Cannot declare namespace in script code
> class A {}
> typeof(A).FullName
"Submission#0+A"
csi.exe
csi is the oldest of the tools. Its main limitation is that it runs on .NET Framework 4.8, not on modern .NET:
> System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription
".NET Framework 4.8.10008.0"
That's fine for experimenting with the language and the base class library, but you can't use APIs added in .NET Core and later, and you can't reference libraries that only target modern .NET.
Default references and using directives come from csi.rsp next to csi.exe. It includes using static System.Console, so in csi you can write WriteLine("hi") without the Console. prefix.
Useful options:
csi start the REPL
csi script.csx a b c run script.csx with arguments a, b, c
csi -i script.csx run script.csx, then stay in the REPL
csi -r:MyLib.dll -u:MyLib add a reference and a using directive
#r in csi accepts only assembly names and paths (#r "System.Net.Http", #r "bin\MyLib.dll"). NuGet references fail:
> #r "nuget: Humanizer.Core, 2.14.1"
error CS0006: Metadata file 'nuget: Humanizer.Core, 2.14.1' could not be found
C# Interactive window in Visual Studio
Visual Studio has the same REPL in a tool window: View > Other Windows > C# Interactive. It adds syntax highlighting, IntelliSense and a few extra commands:
#resetclears all state and starts over (#reset coreswitches to a .NET Core host,#reset 64to a 64-bit .NET Framework host).#clsclears the window.- Right-click a project in Solution Explorer and pick Initialize Interactive with Project. This builds the project and references its output and dependencies, so you can call your own code from the REPL.
- Select code in the editor and press Ctrl+E, Ctrl+E to send it to the interactive window.
dotnet-script
dotnet-script is a .NET global tool that runs .csx scripts and provides a REPL on modern .NET. Its big feature is NuGet support.
Install it:
dotnet tool install -g dotnet-script
Run dotnet-script without arguments to start the REPL:
> System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription
".NET 10.0.12"
> #r "nuget: Humanizer.Core, 2.14.1"
> using Humanizer;
> "some_variable_name".Humanize()
"some variable name"
> TimeSpan.FromMinutes(135).Humanize(2)
"2 hours, 15 minutes"
#r "nuget: Package, Version" downloads the package (and its dependencies) and references it. Leave out the version to get the latest. Type #exit to leave the REPL.
Scripts
A .csx file is a script in the same dialect. Here's a script that uses a NuGet package, loads helper code from another script and reads command-line arguments.
helpers.csx:
public static string Banner(string s) => $"== {s} ==";
report.csx:
#!/usr/bin/env dotnet-script
#r "nuget: Humanizer.Core, 2.14.1"
#load "helpers.csx"
using Humanizer;
Console.WriteLine(Banner("report"));
Console.WriteLine($"args: {string.Join(", ", Args)}");
var dir = Args.Count > 0 ? Args[0] : ".";
foreach (var f in new DirectoryInfo(dir).GetFiles("*.csx").OrderBy(f => f.Name))
{
Console.WriteLine($"{f.Name,-12} {f.Length.Bytes().Humanize("0.0")}");
}
> dotnet-script report.csx -- . extra
== report ==
args: ., extra
helpers.csx 55.0 B
report.csx 564.0 B
Things to note:
- Arguments after
--are available in the globalArgs(anIList<string>). Without--,dotnet-scriptmay interpret them as its own options. #loadpaths are relative to the script file, not the current directory.#rand#loadmust come before any other code, at the top of the file.- The first run is slow because the script is compiled and packages are restored. The compiled result is cached, so later runs of an unchanged script start quickly.
- On Linux and macOS, the
#!line pluschmod +x report.csxlets you run./report.csxdirectly. On Windowsdotnet-script registerassociates.csxfiles withdotnet-script.
A script can return an exit code with a top-level return:
if (Args.Count == 0)
{
Console.Error.WriteLine("usage: check.csx <file>");
return 2;
}
Console.WriteLine(File.Exists(Args[0]) ? "found" : "missing");
return File.Exists(Args[0]) ? 0 : 1;
> dotnet-script check.csx
usage: check.csx <file>
> echo $?
2
> dotnet-script check.csx -- nope.txt
missing
> echo $?
1
The same script runs unchanged in csi (csi check.csx nope.txt), as long as it doesn't use NuGet references.
Other commands:
dotnet-script eval "Console.WriteLine(Enumerable.Range(1, 5).Sum())"evaluates code passed on the command line.dotnet-script -i script.csxruns a script and drops into the REPL with its state.dotnet-script initcreates a sample script plus VS Codelaunch.jsonso you can debug scripts with breakpoints.dotnet-script publish script.csxturns a script into an executable.
csharprepl
csharprepl is a REPL focused on the interactive experience: syntax highlighting as you type, IntelliSense completion, signature help, documentation lookup (F1 opens the docs for the symbol under the cursor) and pretty-printed output. It's the closest thing to the Visual Studio interactive window in a terminal.
dotnet tool install -g csharprepl
csharprepl
It supports NuGet packages, assemblies and even whole projects:
> #r "nuget: Humanizer.Core, 2.14.1"
> using Humanizer;
> "PascalCaseName".Humanize()
"Pascal case name"
csharprepl -r MyApp.csproj reference a project (it's built first)
csharprepl -f Microsoft.AspNetCore.App reference the ASP.NET Core shared framework
csharprepl -u System.Text.Json add a using directive
csharprepl script.csx run script.csx, then start the REPL
It also has a one-shot mode handy for quick calculations from the shell:
> csharprepl -e "Math.Sqrt(2)"
1.4142135623730951
> csharprepl -e "new List<int> { 1, 2, 3 }"
List<int>(3) { 1, 2, 3 }
Ctrl+Enter shows a detailed view of the result (all properties of an object, full exception stack traces). Options can be saved in a config.rsp file (csharprepl --configure opens it) so you don't have to repeat them.
File-based programs: dotnet run app.cs
Since .NET 10 the SDK can run a single .cs file directly, with no project file. This isn't a REPL and it isn't the script dialect: it's a normal C# program with top-level statements. But it covers most of what people used .csx scripts for, and needs nothing beyond the SDK.
hum.cs:
#!/usr/bin/env -S dotnet run
#:package Humanizer.Core@2.14.1
using Humanizer;
Console.WriteLine(TimeSpan.FromSeconds(4000).Humanize(2));
Console.WriteLine($"args: {string.Join(", ", args)}");
> dotnet run hum.cs -- a b
1 hour, 6 minutes
args: a, b
#:package Name@Version replaces #r "nuget: ...". Arguments are in the usual args array. On Unix the shebang line makes the file directly executable.
You can even pipe code into dotnet run -:
> echo 'Console.WriteLine(string.Join(" ", Enumerable.Range(1, 5).Select(i => i * i)));' | dotnet run -
1 4 9 16 25
Compared to .csx scripts, file-based programs:
- are full C#: you can declare namespaces, and the code behaves exactly the same as in a project
- are supported by Microsoft and the C# extension in VS Code
- can be converted to a regular project with
dotnet project convert hum.cswhen they outgrow a single file - don't print expression values and have no REPL
See Building and distributing programs for more about building and publishing.
Building your own REPL with the scripting API
The engine behind csi, dotnet-script and csharprepl is available as the Microsoft.CodeAnalysis.CSharp.Scripting NuGet package. RoslynScript and Simple code evaluation show how to evaluate a single expression. A REPL needs one more thing: each submission must continue from the state of the previous one. That's what ScriptState.ContinueWithAsync does.
Here's a complete REPL in about 40 lines. It also exposes a host object (Globals), whose members scripts can use as if they were global variables and functions. This is how you'd add a scripting console to an application: give the scripts access to your application's objects through the globals.
repl.cs:
#:package Microsoft.CodeAnalysis.CSharp.Scripting@5.9.0
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
var options = ScriptOptions.Default
.AddImports("System", "System.Linq", "System.Collections.Generic")
.AddReferences(typeof(Enumerable).Assembly);
var globals = new Globals { Prices = new() { ["apple"] = 1.25m, ["pear"] = 0.80m } };
ScriptState<object>? state = null;
while (true)
{
Console.Write("> ");
string? line = Console.ReadLine();
if (line is null || line == "#exit") break;
if (string.IsNullOrWhiteSpace(line)) continue;
try
{
state = state is null
? await CSharpScript.RunAsync(line, options, globals)
: await state.ContinueWithAsync(line, options);
if (state.ReturnValue is not null)
Console.WriteLine(state.ReturnValue);
}
catch (CompilationErrorException e)
{
Console.WriteLine(string.Join(Environment.NewLine, e.Diagnostics));
}
catch (Exception e)
{
Console.WriteLine($"{e.GetType().Name}: {e.Message}");
}
}
if (state is not null)
{
foreach (var v in state.Variables)
Console.WriteLine($"{v.Name} : {v.Type.Name} = {v.Value}");
}
public class Globals
{
public Dictionary<string, decimal> Prices { get; set; } = new();
public decimal Total(params string[] items) => items.Sum(i => Prices[i]);
}
A session (dotnet run repl.cs):
> Prices.Count
2
> var basket = new[] { "apple", "apple", "pear" };
> Total(basket)
3.30
> int Double(int x) => x * 2;
> Double(21)
42
> Prices["kiwi"] = 2.10m;
> Total("kiwi", "pear")
2.90
> basket.Lenght
(1,8): error CS1061: 'string[]' does not contain a definition for 'Lenght' and no accessible extension method 'Lenght' accepting a first argument of type 'string[]' could be found (are you missing a using directive or an assembly reference?)
> Prices["mango"]
KeyNotFoundException: The given key 'mango' was not present in the dictionary.
> #exit
basket : String[] = System.String[]
How it works:
CSharpScript.RunAsynccompiles and runs the first submission and returns aScriptState<object>.state.ContinueWithAsync(code)compiles the next submission so that it sees everything declared before, runs it, and returns a new state. Each state is immutable, so you could keep old states around to implement undo.state.ReturnValueis the value of a trailing expression, ornullfor statements.- Compile errors throw
CompilationErrorExceptionwith the diagnostics. Becausestateis only replaced on success, a bad submission doesn't destroy the session. Runtime exceptions propagate as is. - Public members of the globals object (
Prices,Total) are accessible to scripts without qualification. The globals type must be public. state.Variableslists variables declared by scripts (not methods, and not the globals).
A few caveats if you embed scripting in a real application:
- Every submission is compiled into a new in-memory assembly that is never unloaded. A long-running REPL slowly accumulates memory.
- Compilation is slow the first time (hundreds of milliseconds while Roslyn warms up), fast afterwards.
- Scripts run in your process with full trust. They can do anything your program can: read files, start processes, call
Environment.Exit. Never run scripts from untrusted users. - The scripting package pulls in the whole Roslyn compiler, adding over 10 MB to your app, and isn't compatible with Native AOT or trimming.
Which one to use
- To try out a snippet or explore an API:
csharpreplin a terminal, or the C# Interactive window if you're already in Visual Studio. - For a utility script you'll keep and rerun: a file-based program with
dotnet run app.cs. It needs nothing beyond the .NET SDK and is plain C#. - For existing
.csxscripts, or if you want the script dialect (printed expression values,#load):dotnet-script. - To let users of your application run C# code: the Roslyn scripting API.