Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16310

How to pass an object to a script?

In the following snippet, how do I pass my object as parameter to the method in the script?

var c = new MyAssembly.MyClass()
{
    Description = "test"
};

var code = "using MyAssembly;" +
           "public class TestClass {" +
           "  public bool HelloWorld(MyClass c) {" +
           "    return c == null;" +
           "  }" +
           "}";

var script = CSharpScript.Create(code, options, typeof(MyAssembly.MyClass));
var call = await script.ContinueWith<int>("new TestClass().HelloWorld()", options).RunAsync(c);

Upvotes: 8

Views: 4953

Answers (1)

krontogiannis
krontogiannis

Reputation: 1939

The Globals type should hold any global variable declarations as it's properties.

Assuming you got the correct references for your script:

var metadata = MetadataReference.CreateFromFile(typeof(MyClass).Assembly.Location);

Option 1

You need to define a global var of type MyClass:

public class Globals
{
    public MyClass C { get; set; }
}

And use that as a Globals type:

var script = 
    await CSharpScript.Create(
        code: code,
        options: ScriptOptions.Default.WithReferences(metadata),
        globalsType: typeof(Globals))
    .ContinueWith("new TestClass().HelloWorld(C)")
    .RunAsync(new Globals { C = c });

var output = script.ReturnValue;

Note that in the ContinueWith expression the is a C variable as well as a C property in Globals. That should do the trick.


Option 2

In your case it might make sense to create a delegate if you intend to call the script multiple times:

var f =
    CSharpScript.Create(
        code: code,
        options: ScriptOptions.Default.WithReferences(metadata),
        globalsType: typeof(Globals))
    .ContinueWith("new TestClass().HelloWorld(C)")
    .CreateDelegate();

var output = await f(new Globals { C = c });

Option 3

In your case you don't even need to pass any Globals

var f =
    await CSharpScript.Create(
        code: code,
        options: ScriptOptions.Default.WithReferences(metadata))
    .ContinueWith<Func<MyClass, bool>>("new TestClass().HelloWorld")
    .CreateDelegate()
    .Invoke();

var output = f(c);

Upvotes: 14

Related Questions