Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16320

Pass parameter to a method and read the return value?

Having this code:

var code = "public class TestClass {" +
           "  public int HelloWorld(int num) {" +
           "    return 5 + num;" +
           "  }" +
           "}";

var script = CSharpScript.Create(code);
var x = (await script.RunAsync()).ReturnValue;

How does one pass a value for the parameter, call the method and read the return value?

Upvotes: 1

Views: 1403

Answers (1)

Tommy
Tommy

Reputation: 3124

Continue with another code is the simplest.

var call = await script.ContinueWith<int>("new TestClass().HelloWorld(3)").RunAsync();
var x = call.ReturnValue;

By the way, CSharpScript is a scripting engine which does not require you having class and method like ordinary C# program. You can just use 5 + num as script content.

var code = "5 + num";
var numValue = 3;

var setParam = await CSharpScript.RunAsync("var num = " + numValue + ";");
var runCode = await setParam.ContinueWithAsync(code);
var x = runCode.ReturnValue;

For full example, take a look of RoslynScript/Script.cs

Upvotes: 2

Related Questions