简体   繁体   中英

Can I call a C# function from the Immediate Window without compiling my whole project?

Back in my VB6 days, I could use the Immediate Window to run a quick sanity test on a function, even if the rest of my code was in a broken state:

在此处输入图像描述

It was handy for quick and dirty REPL debugging.

When writing C# code in Visual Studio, I can't call any of my code from the Immediate Window unless all of it is valid and compiles.

That works fine when my project is in a ready to run state, but not when I'm in the midst of tearing apart a bunch of code.

Is there any way I can configure the Immediate Window to only compile what's needed for the statement I'm trying to execute? Or other workarounds?

I've heard LINQPad is awesome, but I assume it would require me to copy-paste all the code my test statement depends on before I can run it. I've also played with the newer Interactive Window but don't think it does what I'm hunting for.

From your comment above, you already stumbled on the answer: The C# Interactive window ( View | Other Windows | C# Interactive ) is the feature you want. If the Immediate Window isn't able to run the code you want to run due to existing project errors, then C# Interactive will. Visual Studio's C# Interactive window actually works the same way VB6's Immediate Window works. The C# Interactive window will successfully compile and run code that does not depend on your error-state project code:

在此处输入图像描述

And just like in VB6, you wouldn't be able to access a function or variable from project code that is not compiling--as others have pointed out, how would the compiler possibly work in any "immediate-window" mode if it had to depend on code that cannot compile? By as my image above proves, as long as the code you present to the C# Interactive window is compilable, it will work even when your project code will not.

在此处输入图像描述

As long as you steer clear of any code that might depend on the project code, you even can compile more complex examples, like this:

However, unlike VB6's Immediate window (which is a sort of VB-only hybrid of Visual Studio's Immediate along with Visual Studio's C#/F# Interactive window), you cannot reference values that exist in project code because the C#/F# Interactive window is sandboxed. Thus, in the examples shown, I cannot access ggc.Name in the C# Interactive window--that window doesn't have access to any project variables or state--whether or not the project has compilation errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM