-2

What do I need to to for this to work in C# Visual Studio?

using Roslyn.Scripting; 
using Roslyn.Scripting.CSharp;

namespace RoslynScriptingDemo 
{    
    class Program
    {      
        static void Main(string[] args)
        {
            var engine = new ScriptEngine();            
            var session = Session.Create(); 
            engine.Execute(@"var a = 42;", session); 
            engine.Execute(@"System.Console.WriteLine(a);", session);
        }
    }
}
Cee McSharpface
  • 8,493
  • 3
  • 36
  • 77
  • @raul.vila see the ScriptEngine? Not familiar with C#, but I'm assuming it works simiarlly to the one in Java. It enables the use of other languages inside C#, meaning (here) running JS from C#. The JS tag is there because (in the slightly horribly formatted code) there's JS code – Zoe Apr 18 '18 at 16:20
  • @raul.vila I missclicked. sorry – user9570328 Apr 18 '18 at 16:25
  • what is your question? what is your error? compiler error/runtime exception? – Cee McSharpface Apr 18 '18 at 16:26
  • @dlatikay When I use the Roslyn.Scripting.CSharp I get an Error. Is there something I need to download for it to work? – user9570328 Apr 18 '18 at 16:29
  • what error? can be anything. probably roslyn package not installed? if it is a red intellisense error, try a build and tell us the compiler error it generates. – Cee McSharpface Apr 18 '18 at 16:30
  • @dlatikay it says: "The type or namespace name 'Roslyn' could not be found. Are you missing a using directive or an assembly reference?" – user9570328 Apr 18 '18 at 17:33
  • you included the using directive. so it can only be the latter. – Cee McSharpface Apr 18 '18 at 18:59
  • @dlatikay How can I fix a missing assembly reference? – user9570328 Apr 19 '18 at 04:56
  • @user9570328 Please see my answer below. I believe that those Roslyn assemblies were in NuGet packages that are no longer available. – asherber Apr 19 '18 at 12:13
  • @asherber Ok. How would This code look like in the current version of Roslyn? – user9570328 Apr 19 '18 at 13:35
  • @user9570328 Please see my answer below. It doesn't say "Roslyn", but that code uses the current version of the Roslyn platform. – asherber Apr 19 '18 at 14:05

1 Answers1

0

That code looks like it was written to use a much older version of Roslyn, and I don't think that NuGet packages to support it are available anymore. Take a look at https://github.com/dotnet/roslyn/wiki/Scripting-API-Samples for information on using Microsoft.CodeAnalysis.CSharp.Scripting, which is current.

Here's how you might do something similar in VS2017:

using Microsoft.CodeAnalysis.CSharp.Scripting;

static async Task Main(string[] args)
{
    var state = await CSharpScript.RunAsync("var a = 42;");
    Console.WriteLine(state.GetVariable("a").Value);
}
asherber
  • 2,508
  • 1
  • 15
  • 12