Get parameters list in a function

Hi folks,

I would like to find a way to iterate through the parameters passed in my function, something like this:

void any MyFunction (int A, ushort B, int[] C)

{

foreach (obj in MyFunction.Parameters())

{

switch(obj.GetType().ToString())

{

case "int":

...

case "ushort":

...

case "int[]":

...

}

}

}

any ideas?

[625 byte] By [alxp] at [2008-1-7]
# 1

Try this

Code Snippet

Type obj_type;
MethodInfo method_info;
ParameterInfo Param_info;
obj_type = this.GetType;


method_info = obj_type.GetMethod("MyFunction");
foreach ( Param_info in method_info.GetParameters)

{

Response.Write(Param_info.Name + " - " + Param_info.ParameterType.ToString);

}

First, you have to include System.Reflection namespace

mmHarinath at 2007-10-2 > top of Msdn Tech,.NET Development,.NET Base Class Library...
# 2
You could pass them in all in as an object[]
I'd also suggest that using an if else may make the code more robust as you casn the use the is keyword.

I.e.

void any MyFunction (object[] paramters)

{

foreach (object obj in parameters)

{

if( obj is int )
{
}

else if( obj is ushort)
{
}

}

}


TomPearson at 2007-10-2 > top of Msdn Tech,.NET Development,.NET Base Class Library...
# 3

Using an array of objects is faster, but you'll lose the fact that types are enforced. If you decide to go with an array of objects, consider using the "params" keyword so you don't have to say new object[] { a, b , c} when you call it. Example from MSDN library:

Code Snippet

public static void UseParams2(params object[] list)
{
for ( int i = 0 ; i < list.Length ; i++ )
Console.WriteLine(list[i]);
}

public static void Main()
{
UseParams2(1, 'a', "test");

}

sirjis at 2007-10-2 > top of Msdn Tech,.NET Development,.NET Base Class Library...

.NET Development

Site Classified