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?
Variable length argument is a feature that allows a function to receive any number of arguments. There are situations where we want a function to handle variable number of arguments according to requirement.
va_list is a complete object type suitable for holding the information needed by the macros va_start, va_copy, va_arg, and va_end. If a va_list instance is created, passed to another function, and used via va_arg in that function, then any subsequent use in the calling function should be preceded by a call to va_end.
Variadic functions are functions that can take a variable number of arguments. In C programming, a variadic function adds flexibility to the program. It takes one fixed argument and then any number of arguments can be passed.
You call it with a va_list and a type, and it takes value pointed at by the va_list as a value of the given type, then increment the pointer by the size of that pointer. For example, va_arg(argp, int) will return (int) *argp , and increment the pointer, so argp += sizeof int .
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)
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.
object[] args = new object[] { 2, 4, 6 };
this.GetType().GetMethod("foo").Invoke(this, args);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With