0

Is there an equivalent to func_get_arg (php) in C#?

func_get_arg ( int $arg_num ):

Gets the specified argument from a user-defined function's argument list.

This function may be used in conjunction with func_get_args() and func_num_args() to allow user-defined functions to accept variable-length argument lists.

It basically means the index can be used to get the argument value...

Thanks

Community
  • 1
  • 1
Darren
  • 10,631
  • 8
  • 42
  • 64
  • check this one: http://stackoverflow.com/questions/214086/how-can-you-get-the-names-of-method-parameters-in-c – Davide Piras Dec 07 '11 at 22:57
  • I don't know of anything off hand that does this inside the basic framework of c#. There are some dependency injection frameworks that would support something similar to this. It would be helpful to know what you are trying to accomplish. – Todd Richardson Dec 07 '11 at 22:59
  • Ask what you want to do, now how you want to do it :) –  Dec 07 '11 at 23:05

3 Answers3

3

C# is statically typed, so function signatures matter. You can't just call a method with any number of arguments, which really means there is no need for func_get_arg.

That said, you can get pretty close if you have a method such as this one:

void MyMethod(params object[] args)
{
    var indexOfArgument = 42; // or whatever
    var valueOfArgument = args[indexOfArgument]; // should also check array bounds
}

Of course if all your arguments are typed as System.Object there's not much you can do with them, but from a syntactic viewpoint it's close (plus, you could also have a method that accepts params T[] args for any type T).

Jon
  • 428,835
  • 81
  • 738
  • 806
  • @Darren: From MSDN: "The [`params`](http://msdn.microsoft.com/en-us/library/w5zay9db(v=VS.100).aspx) keyword lets you specify a method parameter that takes a variable number of arguments." – Jon Dec 07 '11 at 23:01
0

in C# there's a method "__arglist()" or you can easily make a function accept variable number of parameters like this

int Average(params int[] ints)
{
int total = 0;
foreach(int i in ints) // loop to the number of parameters
    total += i;
return (ints.Length > 0 ? total / ints.Length : 0);
}
Evan Lévesque
  • 3,115
  • 7
  • 40
  • 61
0

As I understand it, the purpose of func_get_arg in PHP is to have a variable number of arguments to a function. Here's the equivilent to that in C#:

public void Foo(string realArg, int anotherRealArg, params int[] variableArgs)
{
    Console.WriteLine("My real string argument was " + realArg);
    Console.WriteLine("My real integer argument was " + anotherRealArg);
    Console.WriteLine("And I was given " + variableArgs.Length + " extra arguments");
}

// Usage
Foo("Bar", 1, 2, 3, 4, 5);

Within the method, variableArgs is a regular array. Before accessing it, you'll want to check its Length to be sure you don't get an IndexOutOfRangeException.

David Yaw
  • 27,383
  • 4
  • 60
  • 93