C# Interactive

suggest change

C# 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:

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:

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:

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:

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:

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:

A few caveats if you embed scripting in a real application:

Which one to use

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents