arrow-left arrow-right brightness-2 chevron-left chevron-right circle-half-full dots-horizontal facebook-box facebook loader magnify menu-down RSS star Twitter twitter GitHub white-balance-sunny window-close
Strongly-typed Names for INotifyPropertyChanged
1 min read

Strongly-typed Names for INotifyPropertyChanged

This is an old post and doesn't necessarily reflect my current thinking on a topic, and some links or images may not work. The text is preserved here for posterity.

A number of people have asked whether it is possible to implement INotifyPropertyChanged without hard-coding property names as strings inside code.

For example, you would normally write:

public string FirstName
{
    get { return _firstName; }
    set
    {
        _firstName = value;
        OnPropertyChanged(new PropertyChangedEventArgs("FirstName"));
    }
}

Unfortunately the default refactoring tools won't search in string literals, so if LastName was renamed to Surname, you'd need to change the string manually.

One option to enforce compile-time detection would be the following:

public string FirstName
{
    get { return _firstName; }
    set
    {
        _firstName = value;
        OnPropertyChanged(Property.GetFor( () => this.Name ));
    }
}

It could be implemented quite simply with the following static method:

public class Property
{
    public static PropertyChangedEventArgs GetFor(Expression<Func<object>> propertyNameLambda)
    {
        MemberExpression member = propertyNameLambda.Body as MemberExpression;
        if (member != null)
        {
            return new PropertyChangedEventArgs(member.Member.Name);
        }
        return new PropertyChangedEventArgs("");
    }
}

Personally, I don't mind hard-coding property names too much, but it's hardly a best practices, so you may find the above useful. Just beware that it does come with some overhead at runtime.

Enjoying these posts? Subscribe for more

Subscribe now
Already have an account? Sign in
Paul Stovell's Blog

Hello, I'm Paul Stovell

I'm a Brisbane-based software developer, and founder of Octopus Deploy, a DevOps automation software company. This is my personal blog where I write about my journey with Octopus and software development.

I write new blog posts about once a month. Subscribe and I'll send you an email when I publish something new.

Subscribe

Comments

You've successfully subscribed to Paul Stovell's Blog.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.