Colonel Panic
Colonel Panic

Reputation: 137524

Can the C# interactive window interact with my code?

In Visual Studio 2015 or later, I can open the 'C# interactive window', and run code:

> 5 + 3
8

That's cute. Now how can I interact my code—my classes? Assume I have a project open.

> 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?)

Upvotes: 212

Views: 82665

Answers (5)

sloth
sloth

Reputation: 101032

For the latest cross-platform .NET Core/Standard/6/7/... assemblies:

These assemblies are NOT supported by Visual Studio's Initialize Interactive with Project feature per open Roslyn work item here.

Also, Visual Studio versions before 2015 do not support this feature at all.

References to .NET Core assemblies (such as .dll files) can be added to the C# Interactive Window by using the #r command in the C# Interactive window.

Here is an example usage of the #r command:

#r "C:\\path\\to\\your\DLL\\netstandard2.0\\Newtonsoft.Json.dll"

After running the above command (with the correct DLL path) in the C# Interactive window, the following line will work:

using Newtonsoft.Json;

Alternative Solution: LINQPad


For .NET Framework projects in Visual Studio between 2015 and 2022:

You can open the Interactive window by navigating to Views > Other Windows > C# Interactive,

Then just right click your project and run Initialize Interactive with Project from the context menu.

Alternative Solution: Immediate Window

Immediate Window

Upvotes: 291

Luke Hammer
Luke Hammer

Reputation: 2218

Just an update from the @Botz3000 answer.

The command you want to find is now called "Initialize Interactive with Project"

enter image description here

Also it is worth noting i could not find this command if my C# interactive window was not viewable.

Upvotes: 57

Mahmoud Hanafy
Mahmoud Hanafy

Reputation: 1173

It's worth noting that the feature isn't yet supported in VS 2019 for .Net Core project.

You won't find the option, and it's a known issue as highlighted in this answer "Initialize interactive with Project" is missing for .Net Core Projects in Visual Studio 2019

The workaround is to use #r command (#r "Path/MyDll.dll") to load the assembly manually as seen in the answer above.

Upvotes: 55

Botz3000
Botz3000

Reputation: 39600

You can use classes from your own project.
Just right click on your solution and select "Reset Interactive from Project".

If you need more information, here is the source:
Using the C# Interactive Window that comes with Roslyn – Part 2

Upvotes: 70

beloblotskiy
beloblotskiy

Reputation: 1008

Totally agree "Initialize Interactive with Project" is cool.

My approach is to push classes into a library and use //css_reference in C# script or #r in C# Interactive window

For example:

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

Upvotes: 21

Related Questions