sebastienros / jint

Javascript Interpreter for .NET
BSD 2-Clause "Simplified" License
4.04k stars 558 forks source link

Please support "OptionalAttribute" for optional method parameters of .NET objects #1959

Closed UweKeim closed 2 weeks ago

UweKeim commented 2 weeks ago

Currently I'm evaluating whether to move from Windows Active Scripting (with JScript) to Jint.

This class runs successfully when accessed from a JScript script:

public sealed class Person
{
    public void DoSomething(object a, [Optional] object? b)
    {
        Console.WriteLine(a);
        Console.WriteLine(b);
    }
}

E.g. within a script like:

p.DoSomething(1);
p.DoSomething(1, 2);";

When running it with Jint like this:

using Jint;
using System.Runtime.InteropServices;

public sealed class Person
{
    public void DoSomething(object a, [Optional] object? b)
    {
        Console.WriteLine(a);
        Console.WriteLine(b);
    }
}

public static class Program
{
    public static void Main()
    {
        using var engine = new Engine();

        engine.SetValue("p", new Person());

        var script = @"
            p.DoSomething(1);
            p.DoSomething(1, 2);";

        engine.Evaluate(script);
    }
}

It gives an exception:

Jint.Runtime.JavaScriptException: 'No public methods with the specified arguments were found.'

To fix this, I have to change the code to:

public void DoSomething(object a, object? b = null)
{
    Console.WriteLine(a);
    Console.WriteLine(b);
}

This runs successfully with Jint.

My question

Is it possible (and reasonable) that you add support for the OptionalAttribute attribute?

UweKeim commented 2 weeks ago

Update: I've just discovered that JScript also understands if I do not use the OptionalAttribute and use the = null syntax instead.

So I'm simply changing all my .NET methods that are accessible from within the scripts to use the = null syntax and it seems to work with both Jint and JScript.

I'm closing this now, I hope some day someone finds my posting here and it might help then.