Getting Methodbase and all parameters passed to that method

  • Thread starter Thread starter kplkumar
  • Start date Start date
K

kplkumar

I am trying to get the method and the parameters passed to that method
from the stackTrace.

My code is,

private void GetExecutingMethodInfo()
{
StackTrace trace = new StackTrace(false);

for (int index = 0; index < trace.FrameCount; ++index)
{
StackFrame frame = trace.GetFrame(index);
MethodBase method = frame.GetMethod();

string methodName = method.Name;
ParameterInfo[ ] methodParameters = method.GetParameters();
break;
}
}

I can get the type and names of those parameters. But the issue is to
get the values of those parameters. Does anyone know how to do that?
 
As per my understanding, you cannot get runtime values using StackFrame or
Reflection.

Here is a sample code that shows how can you retrieve runtime parameter
values using param object[]. Most often you would like to use it for logging
purposes.

Thanks, Arif
////////////////////Sample code/////////////////////////////////
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//Sample One
int val = 10;
string name = "Arif";
BusinessFunction1(val,name);

//Sampe Two
int b = 10;
string name2 ="Test";
bool check = true;
BusinessFunction2(b,name2,check);
}

static void BusinessFunction1(int val, string name)
{
LogTrace(val,name);
}
static void BusinessFunction2(int b, string name2, bool check)
{
LogTrace(b,name2,check);
}

public static void LogTrace(params object[] args)
{
StackTrace callStack = new StackTrace(1, true);
StackFrame callingMethodFrame = callStack.GetFrame(0);

if (args == null || args.Length == 0)
{
Console.WriteLine("no parameters");
}
else
{
MethodBase callingMethod = callingMethodFrame.GetMethod();
ParameterInfo[] parameters = callingMethod.GetParameters();

int inParamCount = parameters.Length;
foreach (ParameterInfo parameter in parameters)
if (parameter.IsOut) inParamCount--;

Debug.Assert(inParamCount == args.Length, String.Format("Incorrect
number of arguments. Expected {0} but was {1}.", parameters.Length,
args.Length));

int paramCount = parameters.Length;
int argIndex = 0;
for (int i = 0; i < paramCount; i++)
{
Console.WriteLine(parameters.Name);
if (parameters.IsOut)
Console.WriteLine("<Unknown>");
else
{
if (args[argIndex] == null)
Console.WriteLine("<null>");
else
{
Console.WriteLine(args[argIndex].ToString().Trim());
}
argIndex++;
}
if (i < paramCount - 1)
Console.WriteLine(",");
}
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top