Ioannis Panagopoulos blog

Tutorials on HTML5, Javascript, WinRT and .NET

Finding the property that called a method.

by Ioannis Panagopoulos
There are some cases where we want to call the same method from the getters/setters of the properties of a business object. Within that method we want to differentiate behaviour according to the property that called the metthod. The most straightforward solution is to pass with the method a string parameter with the property's name.

class myBO
{
     private int _id;
     public int Id
     {
             get { return _id;}
             set { _id=value; PropertyChanged("Id");}
     }

     private string _name;
     public string Name
     {
             get { return _name;}
             set { _name=value; PropertyChanged("Name");}
     }

     private void PropertyChanged(string propertyName)
     {

               // Do some work here based on which property called the method
     }
}

We can avoid passing the property's name as  a parameter and discover that, within the PropertyChanged method. We use the System.Diagnostics assembly to do the following:

class myBO
{
     private int _id;
     public int Id
     {
             get { return _id;}
             set { _id=value; PropertyChanged();}
     }

     private string _name;
     public string Name
     {
             get { return _name;}
             set { _name=value; PropertyChanged();}
     }

     private void PropertyChanged()
     {
               String propname = new System.Diagnostics.StackTrace().GetFrame(1).
                                                  GetMethod().Name.Substring(4);

               // Do some work here based on which property called the method
     }
}

The GetMethod() method returns the method that called this method. We need its name so we access the "Name" property. But why do we select the substring from position 4 to the end? This is because the .NET framework translates the getters and setters of the properties internally to methods named get_PropertyName and set_PropertyName. Since we need to get the property name we omit the "get_" and "set_" and thus select the string from position 4 to the end.

This approach can be used without the Substring() methd in any situation where we need to find out at runtime the method that called another method.

blog comments powered by Disqus
hire me