Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get method's parameters names and values from inside method

Tags:

Is there a way in .NET to know what parameters and their values were passed to a method. Reflection way? This will be used from inside the method. It has to be generic so it can be used from any method. This is for logging purposes.

like image 768
Tony_Henrich Avatar asked Jan 17 '11 20:01

Tony_Henrich


People also ask

Can I obtain method parameter name using Java reflection?

You can obtain the names of the formal parameters of any method or constructor with the method java. lang. reflect.

What method can be used to read parameter names?

Full Stack Java developer - Java + JSP + Restful WS + Spring Following is a generic example which uses getParameterNames() method of HttpServletRequest to read all the available form parameters. This method returns an Enumeration that contains the parameter names in an unspecified order.

How to pass Multiple parameters into a method java?

Parameters and Arguments Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.

How parameters work in c#?

In C#, arguments can be passed to parameters either by value or by reference. Passing by reference enables function members, methods, properties, indexers, operators, and constructors to change the value of the parameters and have that change persist in the calling environment.


4 Answers

Call MethodBase.GetCurrentMethod().GetParameters().
However, it is not possible to get the parameter values; due to JIT optimization, they might not even exist anymore.

like image 147
SLaks Avatar answered Sep 22 '22 05:09

SLaks


MethodInfo.GetCurrentMethod() will give you information about the current method and then get information about the parameters using GetParameters().

like image 32
Darin Dimitrov Avatar answered Sep 22 '22 05:09

Darin Dimitrov


What you're trying to do can be achieved easily using aspect oriented programming. There are good tutorials online, I'll point to two of them:

  • http://ayende.com/Blog/archive/2008/07/31/Logging--the-AOP-way.aspx
  • http://www.codeproject.com/KB/cs/UsingAOPInCSharp.aspx
like image 6
sukru Avatar answered Sep 20 '22 05:09

sukru


public void FunctionWithParameters(string message, string operationName = null, string subscriptionId = null)
{
    var parameters = System.Reflection.MethodBase.GetCurrentMethod().GetParameters();
    this.PrintParams(parameters, message, operationName, subscriptionId);

}

public void PrintParams(ParameterInfo[] paramNames, params object[] args)
{
    for (int i = 0; i < args.Length; i++)
    {
        Console.WriteLine($"{paramNames[i].Name} : {args[i]}");
    }
}

enter image description here

like image 4
Natalie Polishuk Avatar answered Sep 21 '22 05:09

Natalie Polishuk