{"id":832,"date":"2009-11-25T21:06:55","date_gmt":"2009-11-25T20:06:55","guid":{"rendered":"http:\/\/www.gamlor.info\/wordpress\/?p=832"},"modified":"2021-03-11T09:44:57","modified_gmt":"2021-03-11T08:44:57","slug":"a-better-inotifypropertychanged-implementation","status":"publish","type":"post","link":"https:\/\/www.gamlor.info\/wordpress\/2009\/11\/a-better-inotifypropertychanged-implementation\/","title":{"rendered":"A Better INotifyPropertyChanged Implementation"},"content":{"rendered":"<p>The <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.componentmodel.inotifypropertychanged.aspx\">INotifyPropertyChanged<\/a>-interface and companions are a well know citizens of the .NET-framework. How do you implement this interfaces?. Does it look similar to this?<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">public<\/span> <span class=\"kwrd\">class<\/span> Person : INotifyPropertyChanged\r\n    {\r\n        <span class=\"kwrd\">private<\/span> <span class=\"kwrd\">string<\/span> firstname = <span class=\"str\">\"\"<\/span>;\r\n        <span class=\"rem\">\/* Other fields for the properties *\/<\/span>\r\n        <span class=\"kwrd\">public<\/span> <span class=\"kwrd\">event<\/span> PropertyChangedEventHandler PropertyChanged;\r\n\r\n        <span class=\"kwrd\">public<\/span> <span class=\"kwrd\">string<\/span> Firstname\r\n        {\r\n            get { <span class=\"kwrd\">return<\/span> firstname; }\r\n            set\r\n            {\r\n                firstname = <span class=\"kwrd\">value<\/span>;\r\n                OnPropertyChanged(<span class=\"str\">\"FirstName\"<\/span>);\r\n            }\r\n        }\r\n        <span class=\"rem\">\/** Other properties **\/<\/span>\r\n\r\n        <span class=\"kwrd\">private<\/span> <span class=\"kwrd\">void<\/span> OnPropertyChanged(<span class=\"kwrd\">string<\/span> propertyName)\r\n        {\r\n            var property = PropertyChanged;\r\n            <span class=\"kwrd\">if<\/span> (<span class=\"kwrd\">null<\/span> != property)\r\n                property(<span class=\"kwrd\">this<\/span>, <span class=\"kwrd\">new<\/span> PropertyChangedEventArgs(propertyName));\r\n        }\r\n    }<\/pre>\n<p>\u00a0<\/p>\n<p>This is a common pattern. Often it\u2019s even uglier because the code in the \u2018OnPropertyChanged\u2019-method is copy &amp; pasted into the property-implementation.<\/p>\n<div id=\"attachment_833\" style=\"width: 310px\" class=\"wp-caption alignnone\"><a href=\"https:\/\/www.gamlor.info\/wordpress\/wp-content\/uploads\/2009\/11\/inotifypropertychange.png\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-833\" class=\"size-medium wp-image-833\" title=\"inotifypropertychange\" src=\"https:\/\/www.gamlor.info\/wordpress\/wp-content\/uploads\/2009\/11\/inotifypropertychange-300x208.png\" alt=\"Dilema of INotifyPropertyChange\" width=\"300\" height=\"208\" srcset=\"https:\/\/www.gamlor.info\/wordpress\/wp-content\/uploads\/2009\/11\/inotifypropertychange-300x208.png 300w, https:\/\/www.gamlor.info\/wordpress\/wp-content\/uploads\/2009\/11\/inotifypropertychange.png 1024w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/a><p id=\"caption-attachment-833\" class=\"wp-caption-text\">Dilema of INotifyPropertyChange<\/p><\/div>\n<p>So what makes me sad about this common implementation?<\/p>\n<p>1. First you need to implement the code in \u2018OnPropertyChanged\u2019 over and over. Of course you can build a base-class for this. However I try to be careful with inheritance. Therefore I really don\u2019t like just inherit for this purpose.<\/p>\n<p>2. The property name is a string and that pretty bad here: You have no assistance from the compiler. When you refactor the property-name or make a typo you have introduce a very subtle bug into your program. If your lucky you catch is with unit-test. But honestly, I concentrate my unit test on more important stuff than validating properties.<\/p>\n<p>Now the goal is clear. I want a implementation which has this properties:<\/p>\n<p>1. Reusing the code in the \u2018OnPropertyChanged\u2019-method without inheritance<\/p>\n<p>2. Static type safety, my compiler should complain when I make a typo.<\/p>\n<p>My effort resulted in this:<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">public<\/span> <span class=\"kwrd\">string<\/span> Firstname\r\n{\r\n    get { <span class=\"kwrd\">return<\/span> firstname; }\r\n    set\r\n    {\r\n        firstname = <span class=\"kwrd\">value<\/span>;\r\n        PropertyChanged.Fire(<span class=\"kwrd\">this<\/span>,()=&gt;Firstname);\r\n    }\r\n}<\/pre>\n<p>Now you can call \u201cFire\u201d on all PropertyChangedEventHandler-events. The \u2018Fire\u2019-Implementation is an extension-method which implements the boiler-plate: Checking for null etc. To avoid the string as property-name you pass in a lambda-expression. This avoid typos and makes refactoring safer.<\/p>\n<p>Of course it\u2019s not perfect. You could still pass something wrong with the lambda. The implementation only checks that it&#8217;s a property. But it\u2019s way better than a pure string.<\/p>\n<p>You could extend the implementation to other event-types quite easy. For example for the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.componentmodel.inotifypropertychanging.aspx\">INotifyPropertyChanging<\/a>-interface. The source is attached to this post. Have fun with it.<\/p>\n<p>Implementation: <a href=\"https:\/\/www.gamlor.info\/wordpress\/wp-content\/uploads\/2009\/11\/NotifyExtensions.cs\">NotifyExtensions.cs<\/a>, <a href=\"https:\/\/www.gamlor.info\/wordpress\/wp-content\/uploads\/2009\/11\/TestNotifyExtensions.cs\">TestNotifyExtensions.cs<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The INotifyPropertyChanged-interface and companions are a well know citizens of the .NET-framework. How do you implement this interfaces?. Does it look similar to this? public class Person : INotifyPropertyChanged {&hellip; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":"","_links_to":"","_links_to_target":""},"categories":[126],"tags":[21,24],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/posts\/832"}],"collection":[{"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/comments?post=832"}],"version-history":[{"count":4,"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/posts\/832\/revisions"}],"predecessor-version":[{"id":3747,"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/posts\/832\/revisions\/3747"}],"wp:attachment":[{"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/media?parent=832"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/categories?post=832"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/tags?post=832"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}