Coder Perfect

Is my code compatible with the C# interactive window?

Problem

I can access the ‘C# interactive window’ in Visual Studio 2015 or later and run the following code:

> 5 + 3
8

That’s adorable. Now, how am I going to connect with my code—my classes? Assume I’m working on a project.

> new Cog()
(1,5): error CS0246: The type or namespace name 'Cog' could not be found (are you missing a using directive or an assembly reference?)

Asked by Colonel Panic

Solution #1

Between 2015 and 2022, when you use Visual Studio:

Navigate to Views > Other Windows > C# Interactive to open the Interactive window.

Then, from the context menu, right-click your project and select Initialize Interactive with Project.

For older versions:

To utilise the C# Interactive Window with your code, make sure you build it first, then use the #r command to add a reference to the generated assembly:

You can also interact with your code using the Immediate Window, as shown below:

Answered by sloth

Solution #2

Classes from your own project can be used. Simply right-click on your solution and choose “Reset Interactive from Project” from the context menu.

Here’s where you can get additional information: Part 2 of using the C# Interactive Window included with Roslyn

Answered by Botz3000

Solution #3

Just a follow-up to @Botz3000’s response.

“Initialize Interactive with Project” is the command you’re looking for.

It’s also worth noting that if my C# interactive window was not visible, I couldn’t discover this command.

Answered by Luke Hammer

Solution #4

It’s worth mentioning that the capability isn’t yet available for.Net Core projects in Visual Studio 2019.

You won’t find it, and it’s a known issue, as noted in this response “Initialize interaction with Project” is missing for. Visual Studio 2019 Net Core Projects

The fix is to manually load the assembly using the #r command (#r “Path/MyDll.dll”), as shown in the response above.

Answered by Mahmoud Hanafy

Solution #5

I agree that “Initialize Interactive with Project” is a great idea.

My strategy is to put classes in a library and reference them with /css reference in a C# script or #r in a C# Interactive window.

For example:

#r "D:\\dev\\DbHMonData\\LoadH2Stats\\bin\\Debug\\DbHMonStats.dll"
using DbHMonStats;

Answered by beloblotskiy

Post is based on https://stackoverflow.com/questions/11135571/can-the-c-sharp-interactive-window-interact-with-my-code