Jint: using CLR object 's properties in Javascript functions

619 Views Asked by At

I have been testing the jint library and hit a snag. Given this class in C#:

public class Foo
{
    public string Name { get; } = "Bar";
}

And this code:

Engine engine = new Engine(x => x.AllowClr());

object rc = _engine
    .SetValue("foo", new Foo())
    .Execute("foo.Name.startsWith('B')")
    .GetCompletionValue()
    .ToObject();

I get the error: 'Jint.Runtime.JavaScriptException: 'Object has no method 'startsWith'''

This works, however:

"foo.Name == 'Bar'"

So can I get the former to work?

1

There are 1 best solutions below

0
On

Support for extension methods is added here. But can't get it to work with the .NET string extension methods directly, it does work with an intermediate extensions class.

Update: The string methods like StartsWith aren't real extension methods indeed.

Looks like startsWith is already supported natively now. Replaced GetCompletionValue with the suggested Evaluate

// Works natively with Jint 3.0.0-beta-2032
Engine engine = new Engine();

bool result = engine
    .SetValue("foo", new Foo())
    .Evaluate("foo.Name.startsWith('B')")
    .AsBoolean();

I've tried to add the string extension methods, but that doesn't seem to work. But using your own class for the extension methods and use it that way does work.

public static class CustomStringExtensions
{
    public static bool StartsWith(this string value, string value2) =>
      value.StartsWith(value2);
}

Engine engine = new Engine(options =>
{
    options.AddExtensionMethods(typeof(CustomStringExtensions));
});

bool result = engine
    .SetValue("foo", new Foo())
    .Evaluate("foo.Name.StartsWith('B')")
    .AsBoolean();

I've asked about the native extension methods support here, as I'm curious if and how it is supposed to work.