gsharp gsharp - 3 years ago 361
C# Question

Create a function with CSharpScript and execute it

Is it possible to define a function as a Script and then run it ?

I'm trying to achive something like that:

//defined in a namespace
public class Params{public string input { get; set; }}

string script = "string TryToUpper(string input){ return input.ToUpper(); }";
var v = CSharpScript.Create(script, globalsType: typeof(Params) );

// what to do to execute TryToUpper and get "GIUSEPPE" back?
var val = v.RunAsync(???);

Answer Source

You have to do two things in that script: first, define the function, then actually run it and return it's result. Like this:

public class Params
    public string input;

Params globals = new Params();
globals.input = "some lowercase text";

string script = "string TryUpper(string str) { return str.ToUpper(); } return TryUpper(input);";

string result = await CSharpScript.EvaluateAsync<string>(script, globals: globals);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download