HamedFathi
HamedFathi

Reputation: 3979

How to execute a method in class with C# ScriptEngine

How can I get the result of this source

var src = @"public class Test
{
    public IList<string> CallMe(int count = 10)
    {
        return Enumerable.Range(0, count).Select(x => $""Number-{x}"").ToList();
    }
}";

by Roslyn ScriptEngine in C#?

How can I do this?

object result = await CSharpScript.EvaluateAsync("new Test().CallMe(20)");

Upvotes: 2

Views: 890

Answers (1)

George Alexandria
George Alexandria

Reputation: 2936

The one of way to do that is use continuation from Roslyn Scripting that keeps the previous state of execution:

var src = @"public class Test
{
    public IList<string> CallMe(int count = 10)
    {
        return Enumerable.Range(0, count).Select(x => $""Number-{x}"").ToList();
    }
}";

var options = ScriptOptions.Default
    .AddReferences("mscorlib", "System.Core") // assume that it's run under .netframework
    .AddImports("System", "System.Linq", "System.Collections.Generic");

var list = CSharpScript.RunAsync(src, options).Result
                       .ContinueWithAsync<IList<string>>("new Test().CallMe(20)").Result.ReturnValue;

Upvotes: 2

Related Questions