Discovering calling method name and its parameters

G

Guest

Here is a method that calls a static GetInfo() method on the MyObject class.

public void MethodName(string param1, int param2)
{
MyObject.GetInfo();
}

Is there any way for the GetInfo() method to find out the name and
parameters of the method it was called from?

For example

public static void GetInfo()
{
// Is there some query I can make that would return the name 'MethodName'
// and the names of its parameters 'param1' and 'param2' and their values?
}

Can this be done with System.Reflection?

Joe
 
P

Patrice

See the StackFrame class. You can have the name of the method. Likely its
parameters (you have this info anyway in reflection). Not sure though about
the values.

Please let us know about your findings...

Patrice
 
I

Imran Koradia

Joe,

As Patrice mentioned, you can get the method information using the Stackframe
class. Here's how you would do it:

Imports System.Reflection
Imports System.Diagnostics

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
TestStackFrame()
End Sub

Private Sub TestStackFrame()
' 0 means start from current stack frame
Dim oTrace As New StackTrace(0, True)
' 0 means the current stack frame, 1 means previous, etc
Dim oMethod As MethodBase = oTrace.GetFrame(1).GetMethod
MessageBox.Show(oMethod.Name)
For Each oParam As ParameterInfo In oMethod.GetParameters()
MessageBox.Show(oParam.Name & " - " & oParam.ParameterType.Name)
Next
End Sub

The above code will print out Button1_Click and its parameters.

However!
I'm not sure there's an easy way to get the parameter values. You surely
cannot get the values using either reflection or the Stack classes. You might
be able to use debugger APIs to get the values but that might be a little
more complicated. I haven't seen anyone do this before so I would surely
love to know if you find a way to get the method parameter values.


hope that helps..
Imran.
 

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

Top