0 Comments

C# Interactive is a handy tool for quickly running a piece of code, either line by line or from a script.

The C# Interactive window in Visual Studio is opened from:

View => Other Windows => C# Interactive

Type in one block of C# at a time, terminating with a ; when the block is complete, eg:

A

The same code can also be executed from the command line, without running Visual Studio.

Open the Developer Command Prompt for Visual Studio (which will ensure required paths are set-up for you).

Start the C# Interactive Compiler, with the csi command.

Enter code as for the C# Interactive window, above:

B

To exit csi type CTRL+C

The code can also be saved in a script, eg demo.csx:

using System;

var items = new[] { 'A', 'B', 'C' };

foreach (var item in items)
{
    Console.Write(item);
}

This can be run in the C# Interactive window using the #load command, eg:

#load "C:\Temp\Demo.csx"

which will immediately run the script:

C

Note that the C# Interactive window uses a search path starting at C:\Users\name whereas you might expect it to start from the root of your project.

You can change this by running:

Environment.CurrentDirectory = "C:\your-path"

This is slightly easier from the Developer Command Prompt, where you can just change the path to the root of your project before starting csi, eg:

cd c:\your-path

To reference assemblies use:

#r "path/MyAssembly.dll"

Whether the path is relative or absolute will depend on the context, as for #load, above.

The #r command can be used when working line-by-line, or added to the top of a .csx script.


References

https://github.com/dotnet/roslyn/wiki/Interactive-Window

https://github.com/dotnet/roslyn/wiki/C%23-Interactive-Walkthrough

https://docs.microsoft.com/en-us/archive/msdn-magazine/2016/january/essential-net-csharp-scripting

Post comment