3

I have this code and I am using it to raise the PropertyChanged event without passing the name of property to the function.

private void RaisePropertyChanged<TValue>(Expression<Func<TValue>> propertySelector)
    {
        var memberExpression = propertySelector.Body as MemberExpression;
        if (memberExpression != null)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(memberExpression.Member.Name));
            }
        }
    }

and I am calling it in this way:

  this.RaisePropertyChanged(() => this.IsReady);

Which will raise the PropertyChanged event for the IsReady property. I like the idea as writing code in this way will help to change the name of the property very easily.

Now I want to use the same technique to pass the name and value of a property to a method. Is there any way that I can do this?

2

2 Answers 2

4

You already have it:

string name = memberExpression.Member.Name;
TValue value = propertySelector.Compile()();

An alternative would be to look at the member.MemberType, cast to PropertyInfo or FieldInfo respectively:

var member = memberExpression.Member;
string name = member.Name;
object value;
switch(member.MemberType) {
    case MemberTypes.Field:
       value = ((FieldInfo)member).GetValue(this);
       break;
    case MemberTypes.Property:
       value = ((PropertyInfo)member).GetValue(this, null);
       break;
    default:
       throw new NotSupportedException(member.MemberType.ToString());
}

However, a simpler approach is... to simply pass the name and value to the method:

Foo("IsReady", IsReady);

It depends a bit on how efficient it needs to be, though (reflection/expression does add an overhead - whether that is significant depends on the context).

Sign up to request clarification or add additional context in comments.

Comments

0

For getting the name you can use memberExpression.Member.Name and for getting the value you could use this.GetType().GetProperty (memberExpression.Member.Name).GetGetMethod().Invoke (this, null).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.