Harsha projects

Yet another Tech blog !

Getting Property/Method Name

leave a comment »

Hope you are using INotifyPropertyChanged and also implemented same. When we are raising the event, we also need to supply the property name, usually we hard-code it. So this article about getting the property name from within the property block(setter block).

Here is the code and comments:

    private string _BindedStringProp;

        public string BindedStringProp
                return _BindedStringProp; 
                _BindedStringProp = value;
                //Following line, RawpropName will have value "set_BindedStringProp"
                string RawpropName = MethodBase.GetCurrentMethod().Name;
                //but we need correct property name which will get when we remove first 4 characters.
                string RequiredPropName = MethodBase.GetCurrentMethod().Name.Substring(4); 
                //Following is best way to get the Property Method.

        private void RaisePropertyChanged([CallerMemberName] string propertyName = "")
            //[CallerMemberName] is doing all the magic.
            if (PropertyChanged != null && !string.IsNullOrEmpty(propertyName))
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

            //But when you check the same in a method, we will get correct method name and 
            //no substring is required.
            string propName = MethodBase.GetCurrentMethod().Name;

Please leave your comments.

Thank you.


Written by Harsha

August 27, 2014 at 12:46 AM

Posted in C Sharp, WPF

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: