none
Can a subroutine, function, or property divulge its name? RRS feed

  • Question

  • Being able to return the name of a subroutine, function, or property using a keyword such as "#name" would be a useful convenience for a number of scenarios, such as error logging, implementing INotifyPropertyChanged, and so forth. For example, instead of typing the string "PhoneNumber" in the line  << NotifyPropertyChanged("PhoneNumber") >>  (see code snippet below) I'd like to be able to type

    NotifyPropertyChanged(#name)  or something like that.  Would this be possible to implement given the way the language is compiled?

    Public Property PhoneNumber() As String
            Get
                Return Me.phoneNumberValue
            End Get

            Set(ByVal value As String)
                If Not (value = phoneNumberValue) Then
                    Me.phoneNumberValue = value
                    NotifyPropertyChanged("PhoneNumber")
                End If

            End Set
        End Property

    Wednesday, August 5, 2009 3:59 AM

Answers

  • Well, you can view the callstack to see what method invoked the OnPropertyChanged.

                // Get stacktrace
                System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace();
                System.Diagnostics.StackFrame[] stackFrames = stackTrace.GetFrames();
    
                // Get previous method
                System.Diagnostics.StackFrame previousFrame = stackFrames[stackFrames.Length - 1];
                System.Reflection.MethodBase methodBase = previousFrame.GetMethod();

    Geert van Horrik - CatenaLogic
    Visit my blog: http://blog.catenalogic.com
    Wednesday, August 5, 2009 7:03 AM