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.
You can obtain the names of the formal parameters of any method or constructor with the method java. lang. reflect.
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.
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.
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.
Call MethodBase.GetCurrentMethod().GetParameters()
.
However, it is not possible to get the parameter values; due to JIT optimization, they might not even exist anymore.
MethodInfo.GetCurrentMethod()
will give you information about the current method and then get information about the parameters using GetParameters()
.
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:
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]}");
}
}
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