RecentComments

Comment RSS

Finding the property that called a method.

by Ioannis 11. November 2008 01:28
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.

Tags:

.NET

Add comment


(Will show your Gravatar icon)

Enter the word
CAPTCHA word
Add 1 to the number above


  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.5.0.7

Programming Blogs - BlogCatalog Blog Directory Add to Technorati Favorites

MVP Award

Ioannis Panagopoulos





This blog is using BlogEngine.Net and is hosted in the hoster below. I have not experienced any problems installing BlogEngine.Net in the host and I am satisfied with the host's response times. Therefore I recommend it.


DiscountASP Add