Passing an array in Clearscript to a C# object

Jun 9, 2014 at 3:35 PM
Hi, I have a c# object I'm adding to the clearscript V8 engine that looks like this:

public class Helpers
{
...
    public int NTimes(int[] values, int targetValue)
    {
        int answer = 0;
        if (values != null)
        {
            foreach (int val in values)
            {
                if (val == targetValue)
                    answer++;
            }
        }

        return answer;
    }
}

I add the helpers class (which contains this function) using this: JavascriptContext.AddHostObject("Helpers", Helpers);


However, when in my javascript I attempt to run code like below I get an argument mismatch exception:

var items = [$A1, $A2, $A3, $A6, $A9, $A12, $A13, $A16, $A19];

var value = Helpers.NTimes(items, 3);


Is this at all related to this thread:
https://clearscript.codeplex.com/discussions/537917

Thank you!
Jun 9, 2014 at 5:16 PM
Hi,

I just wanted to point out that I found a solution...

Here is the modifed NTimes function:
    public int NTimes(dynamic values, int targetValue)
    {
        int answer = 0;

        List<int> intVals = new List<int>();


        for (var i = 0; i < values.length; i++)
            intVals.Add(Convert.ToInt16(values[i]));

            foreach (int val in intVals)
            {
                if (val == targetValue)
                    answer++;
            }


        return answer;
    }

The trick was changing it to a dynamic type and then converting from there into integers.
Coordinator
Jun 10, 2014 at 2:15 AM
Thanks for posting your solution!