The Mask
The Mask

Reputation: 17477

dynamic arguments definition in C#

it's possible write something like:

function foo(a,b,c) {
    return a + b + c; 
}

var args = [2,4,6]; 
var output = foo.apply(this, args);  // 12

C# there a equivalent to .apply of javascript?

Upvotes: 8

Views: 622

Answers (3)

Raymond Chen
Raymond Chen

Reputation: 45172

object[] args = new object[] { 2, 4, 6 };
this.GetType().GetMethod("foo").Invoke(this, args);

Upvotes: 4

IAbstract
IAbstract

Reputation: 19881

It's been a while since I've done any javascript, but I understand that the apply method is a way of creating a delegate. In C# there are a number of ways to do this. I would start with something like this:

class Program
{
    static void Main(string[] args)
    {
        Foo foo = new Foo( );
        Func<int[], int> SumArgs = foo.AddArgs; // creates the delegate instance

        //  get some values
        int[] nums = new[] { 4, 5, 6 };

        var result = SumArgs(nums); // invokes the delegate
        Console.WriteLine("result = {0}", result1);

        Console.ReadKey( );
    }
}

internal class Foo
{
    internal int AddArgs(params int[] args)
    {
        int sum = 0;

        foreach (int arg in args)
        {
            sum += arg;
        }

        return sum;
    }
}

There is another way using LINQ, instead of the foreach, you can use:

    return args.Sum( );

More on creating delegates using Func and Action.

Upvotes: 2

Ryan Gross
Ryan Gross

Reputation: 6525

You can use the params keyword:

object foo(params int[] args) { ... }

You can then call the method like this:

var output = foo(2, 4, 6);

or like this:

var args = new [] {2, 4, 6};
var output = foo(args)

Upvotes: 13

Related Questions