You will no longer have to create small ConsoleApplication projects just to try out a small piece of code (bye bye ConsoleApplication42…). With Interactive Window, developers can get output for small code snippets without any project creation, code file or any assembly. Just type in the code and get the result.
C# Interactive Window is part of Visual Studio which makes it easy to learn new language features and experiment with .NET technologies similar to CShell (not completely) but within Visual Studio.
To open Interactive Window, got to View -> Other Windows and select C# Interactive. As shown below.
Helpful REPL commands to remember before you start:
#help : Display help on specified command, or all available commands and key bindings if none specified.
#clear/#cls : Clears the contents of the editor window, leaving history and execution context intact.
#reset : Reset the execution environment to the initial state, keep history.
As always lets start with Hello World example:
You can see in the above code, we created 2 strings variables str1 & str2 and wrote the output to the console. Important things to note here, 1. A ‘;’ will make the statement part of the execution context. 2. Pressing ‘Enter’ after the statement without ‘;’ executes the context. Like here it displays the output ‘Hello World’. 3. Even after we got the output the execution context is still intact. So if I execute Console.WriteLine(str1 + str2), the output will be the same. Use #reset command to reset the execution context. 4. No need to specify the namespace.
I can also create a method in the execution context, and use it later. like
I created a method HelloName(string name) and calling it in the same context gets me the desired output but when I reset the execution context and call the method again, an error is displayed stating “The name ‘HelloName’ does not exist in the current context”.
You can also save your script in a file on the disk and can execute it via VS Command Prompt (extension is not important).
How to reference a DLL and use it
You use the #r directive to reference a DLL.
I have created a simple class library named SimpleMath.dll for easy learning:
Using the #r directive, I can reference my SimpleMath.dll in the Interactive Window’s execution context.
Documentation : https://github.com/dotnet/roslyn/wiki/interactive-window
Hope this helps.