Run your C# code instantly in Visual Studio (2015 and up)

A lesser known trick introduced in Visual Studio 2015 (Update 1) is the fact that you can instantly run C# code without having to create a dummy project. The new Roslyn compiler has introduced C# Interactive Shell; a REPL engine. The REPL engine provides instant feedback to the user according to the input provided. This means that you do not need any main method or any other magic; just pluck in your C# code and get feedback immediately.

In order to fire up the C# Interactive Shell, go to View -> Other Windows -> C# Interactive.

window
Firing up the C# Interactive Shell

The C# Interactive shell equipped with many features that we are accustomed with when using Visual Studio such as Syntax Highlighting, Code Completion, Intellisense and such.

roslyn1
Sample code running in the C# Interactive shell

When you run the C# Interactive shell by default, it does not take into consideration the code that you’re currently editing; it’ll behave like a basic REPL engine; nothing more. Visual Studio provides functionality to run the shell in the context of the currently loaded project. To do that, right click the desired project and press “Initialize Interactive with Project”. Doing this will allow the C# Interactive shell to work directly with the loaded project.

interactive
Initialize Interative with Project

The C# interactive shell provides a lot of functionality such as making use of the async features seamlessly. One must note that obviously, code will still run synchronously. It also has several other features, which have been thoroughly documented on Roslyn’s Github page.

One must note that this is NOT a replacement for the immediate window. Whilst debugging a process, it seems that the only way to interact immediately with the process is through the immediate window; the Interactive shell does not work. To be honest, it makes sense since the C# interactive shell is intended to run C# code instantly without requiring a running solution, unlike the immediate window.

This feature is an ideal addition to any developer who need to run some experimental /dirty code quickly, without any headache whatsoever. I used to use tools such as LINQPad (it has other uses too through) or sites such as RexTester to try out something quickly. With this tool, such tools are not needed anymore!

Edit: Thanks for spotting the typo Christopher Demicoli!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s