Wednesday, February 15, 2006

Getting the current Method

I have an application that logs information when each method runs:

1 Public Function GetRefundsByID(ByVal id As Integer)

2 'implementation


4 LogMessage(String.Format("GetRefundsByID found {0} records", count))

5 End Function

I dont really like this as I have now hardcoded the name of the function into each method which really sucks when I rename a method.

I managed to figure a way to get the current method name via reflection though (note that reflection can adversley affect performance)

1 Private Function GetCurrentMethodName() As String

2 Dim stackTrace As New StackTrace 'the stack trace

3 Dim stackFrame As StackFrame 'one frame of the stack i.e. the last calling method

4 Dim methodBase As methodBase 'the method info


6 stackFrame = stackTrace.GetFrame(1) 'get the frame that happened just before this method

7 methodBase = stackFrame.GetMethod() 'get the method info from that frame


9 Return methodBase.Name

10 End Function

Now that code is a little ugly so here it is refactored:

1 Public Function GetcurrentMethodName()

2 Return New StackTrace().GetFrame(1).GetMethod().Name

3 End Function

Or if you want to show the parameter signature you can use this:

1 Private Function GetCurrentMethodName() As String

2 Dim methodBase As System.Reflection.MethodBase

3 Dim sb As New System.Text.StringBuilder


5 methodBase = New StackTrace().GetFrame(1).GetMethod()


7 sb.AppendFormat("{0} (", methodBase.Name)

8 For Each param As System.Reflection.ParameterInfo In methodBase.GetParameters()

9 sb.AppendFormat(param.Name & " as " & param.ParameterType().Name)

10 Next

11 sb.AppendFormat(")")


13 Return sb.ToString

14 End Function


Post a Comment

<< Home