Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get an array of the arguments passed to a method?

Say I have a method:

 public void SomeMethod(String p1, String p2, int p3)  {   #if DEBUG     object[] args = GetArguments();     LogParamaters(args);  #endif       // Do Normal stuff in the method  } 

Is there a way to retrieve an array of the arguments passed into the method, so that they can be logged?

I have a large number of methods and want to avoid manually passing the arguments by name to the logger, as human error will inevitably creep in.

I'm guessing it will involve reflection in some form - which is fine, as it will only be used for debugging purposes.

Update

A little more information:

I can't change the method signature of SomeMethod, as it is exposed as a WebMethod and has to replicate the legacy system it is impersonating.

The legacy system already logs the arguments that are passed in. To start with the new implementation will wrap the legacy system, so I'm looking to log the parameters coming into the C# version, so that I can verify the right parameters are passed in in the right order.

I'm just looking to log the argument values and order, not their names.

like image 369
David Henderson Avatar asked Jul 20 '10 09:07

David Henderson


People also ask

Can an array be passed to a method?

You can pass arrays to a method just like normal variables. When we pass an array to a method as an argument, actually the address of the array in the memory is passed (reference). Therefore, any changes to this array in the method will affect the array.

Can you pass an entire array as an argument to the method explain?

C++ does not allow to pass an entire array as an argument to a function. However, You can pass a pointer to an array by specifying the array's name without an index.

How an array can be passed to a function as an argument?

If you want to pass a single-dimension array as an argument in a function, you would have to declare a formal parameter in one of following three ways and all three declaration methods produce similar results because each tells the compiler that an integer pointer is going to be received.

How do you pass an entire array to a method in Java?

Passing Array To The Method In Java To pass an array as an argument to a method, you just have to pass the name of the array without square brackets. The method prototype should match to accept the argument of the array type. Given below is the method prototype: void method_name (int [] array);


1 Answers

If you use Postsharp you can simply add an attribute to the method you want to log. Within this attribute you can write the logging code and also will provide the arguments you need. This is known as cross cutting concerns and AOP (Aspect orientated programming)

like image 162
aqwert Avatar answered Sep 22 '22 12:09

aqwert