C# is not the thing what we thought about like the JavaScript, JavaScript has a global context object for the script running.
But in c# is not so easy (at least the runtime doesn't offer us that function directly).
csi.exe initializes a CommandLineRunner for command interactive while starting. Then create a global context ScriptState<object> to save the execution results(return value, variables, methods). Once you commit the code to the terminal, it appends your code to the global context and compiles the code, and runs again or shows you the error.
But, some private and internal methods or classes prevent you to do like csi.exe do (ScriptBuilder, CSharpScriptCompiler, Script.CreateInitialScript).
### About the Black Magic
It only does two things:
Initialize the environment for the first time you create the sandbox.Grab the internal compiler from runtime.
The update: You now can go without using the black magic.
Make sure you have installed Roslyn nuget package.
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="4.1.0-3.final" />
then type the code
var sandbox = new SandBox();
{
dynamic result = await sandbox.RunAsync("return \"Hello world!\"");
Console.WriteLine(result);
}
You will get a "Hello world!" string output if no exception happens.
https://gist.github.com/AkulaKirov/dbfd77132bd563dcd69e269ad64b45fe
A fix version for error that GlobalTypes not functional for the script.
replace
optionsOpt
intoglobalsTypeOpt
at BlackInteractiveMagic.cs , Line 30.