Freigeben über


Get the name of the current property or method

I often need to obtain the name of the current property of method, and I have historically used reflection for this.  However, I recently ran across the CallerMemberName attribute. This lead me to create the following utility function:

 Public Shared Function GetMethodOrPropertyName(
          <CallerMemberName> Optional memberName As String = Nothing) 
          As String
    Return memberName
End Function

The key here is that I do not specify the memberName parameter when I call the function, so the compiler fills it in for me.  (That's what the attribute is for.)  Now I can call this function whenever I need the current method's name.  NO custom reflection code required.