1

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(???);
2
  • I am not sure this is possible with CSharpScript; what if you create an in-memory assembly (using Roslyn) with that function? Would that be an acceptable solution for your use case? Commented Oct 2, 2017 at 11:30
  • @CoolBots if that's easy to do yes :) My end-goal is to easily have some code snippets that my application can execute Commented Oct 2, 2017 at 11:40

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

4 Comments

I do not really understand why I have to call return TryUpper at the end, but it does what I want :) thanks!
Looks like the entire script is evaluated, and the result assigned to the string in the executing code. You can likely substitute the entire script with string script = "input.ToUpper()"; with the same effect.
Almost. You still need to actually return someting. so, you could replace it with string script = "return input.ToUpper();";
@Avo, I just tried it - works without return, but not with it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.