Properties with property changed event, part 2

Last time I talked about properties with a changed event, I described the traditional pattern of having one event per property. But there is a disadvantage to that approach: since an event needs storage for a delegate, this technique wastes a considerable amount of memory if nobody subscribes to the events.

Say you have 10 properties of reference types with a simple backing variable each. On a 32 bit machine, those will take 40 bytes plus the storage of the actual objects (if any). If each of these properties has an associated event, that's 40 additional bytes (plus storage for the delegate objects, if any).

If you want to monitor if anything changes to the object, no matter which property it is that actually changes, you need to subscribe to all 10 events, and that's going to create 10 delegate objects.

The System.ComponentModel.INotifyPropertyChanged interface provides an interesting alternative. It declares just one event:

public interface INotifyPropertyChanged
{
    event PropertyChangedEventHandler PropertyChanged;
}

A PropertyChangedEventHandler is an event handler that takes an object (sender) and  a PropertyChangedEventArgs, an EventArgs with an additional string PropertyName property.

How do we use this interface? Say I have a class Customer with two string properties: Name and City. It would look like this:

using System;
using System.ComponentModel;

class Customer : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, e);
        }
    }

    private string name;

    public string Name
    {
        get { return name; }
        set
        {
            if (value != name)
            {
                name = value;
                OnPropertyChanged(new PropertyChangedEventArgs("Name"));
            }
        }
    }

    private string city;

    public string City
    {
        get { return city; }
        set
        {
            if (value != city)
            {
                city = value;
                OnPropertyChanged(new PropertyChangedEventArgs("City"));
            }
        }
    }
}

Even though there are two properties, there is only one event. The advantages: less code, less memory usage. There are disadvantages as well though. If you're interested only in changes to the Name property, your event handler needs to test the PropertyName in the PropertyChangedEventArgs passed to you. And you may get a lot of calls notifying you of changes to properties your aren't interested in. On the sending side, be careful with rename refactorings, since the strings being passed around won't be refactored by Visual Studio.

Nevertheless, this approach is becoming the dominant technique for data binding scenarios. In fact, the new Linq to SQL generated classes use this approach as well. So you might just as well get accustomed to it.

In part 3 of this series, we'll have a look at how Windows Forms controls store their event delegates, with a CueBannerTextBox example.


Comments

November 26. 2008 06:15 AM

Nicely presented, clear and concise ... unlike so much other stuff on web. Good Job and Thanks again.

January 9. 2010 07:47 AM

litigation support services

Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon.

litigation support services

January 9. 2010 05:39 PM

dog aggression

Just wanted to give you a shout from the valley of the sun, great information. Much appreciated.

dog aggression

January 10. 2010 12:08 AM

Arabic Tattoo

Nice information, many thanks to the author. It is incomprehensible to me now, but in general, the usefulness and significance is overwhelming. Thanks again and good luck!

Arabic Tattoo

January 10. 2010 06:50 PM

solar garden fountains

I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own BlogEngine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it.

solar garden fountains

January 12. 2010 12:06 AM

free game downloads

Nice information, many thanks to the author. It is incomprehensible to me now, but in general, the usefulness and significance is overwhelming. Thanks again and good luck!

free game downloads

January 14. 2010 11:11 PM

internet marketing information

I was wondering what is up with that weird gravatar??? I know 5am is early and I'm not looking my best at that hour, but I hope I don't look like this! I might however make that face if I'm asked to do 100 pushups. lol

internet marketing information

January 15. 2010 02:49 AM

Astral Projection

Hey - nice blog, just looking around some blogs, seems a pretty nice platform you are using. I'm currently using Wordpress for a few of my sites but looking to change one of them over to a platform similar to yours as a trial run. Anything in particular you would recommend about it?

Astral Projection

January 15. 2010 01:28 PM

lipovox review

Hello,I love reading through your blog, I wanted to leave a little comment to support you and wish you a good continuation. Wishing you the best of luck for all your blogging efforts.

lipovox review

January 22. 2010 12:05 AM

How To Get Rid Of Eczema

I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post

How To Get Rid Of Eczema

January 23. 2010 05:20 AM

trading money management

Just wanted to give you a shout from the valley of the sun, great information. Much appreciated.

trading money management

January 24. 2010 01:17 AM

szerencsejáték

Just wanted to give you a shout from the valley of the sun, great information. Much appreciated.

szerencsejáték

January 24. 2010 10:02 PM

NJ Website Design

Great post! I am just starting out in community management/marketing media and trying to learn how to do it well - resources like this article are incredibly helpful. As our company is based in the US, it?s all a bit new to us. The example above is something that I worry about as well, how to show your own genuine enthusiasm and share the fact that your product is useful in that case.

NJ Website Design

January 28. 2010 08:53 PM

bellanue

Me and my friend were arguing about an issue similar to this! Now I know that I was right. lol! Thanks for the information you post.

bellanue

January 28. 2010 08:59 PM

baby bedding

Hi. this is kind of an "unconventional" question , but have other visitors asked you how get the menu bar to look like you've got it? I also have a blog and am really looking to alter around the theme, however am scared to death to mess with it for fear of the search engines punishing me. I am very new to all of this ...so i am just not positive exactly how to try to to it all yet. I'll just keep working on it one day at a time.

baby bedding

January 30. 2010 10:48 AM

contractor accountants

This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! keep up the good work.

contractor accountants

January 30. 2010 10:50 AM

umbrella payroll

That is some inspirational stuff. Never knew that opinions could be this varied. Thanks for all the enthusiasm to offer such helpful information here.

umbrella payroll

January 31. 2010 10:09 PM

quilts

Have you ever considered adding more videos to your blog posts to keep the readers more entertained? I mean I just read through the entire article of yours and it was quite good but since I'm more of a visual learner,I found that to be more helpful well let me know how it turns out! I love what you guys are always up too. Such clever work and reporting! Keep up the great works guys I've added you guys to my blogroll. This is a great article thanks for sharing this informative information.. I will visit your blog regularly for some latest post.

quilts

February 2. 2010 03:05 AM

tatuaggi

How-do-you-do, just needed you to know I have added your site to my Google bookmarks because of your extraordinary blog layout. But seriously, I think your site has one of the freshest theme I've came across. It really helps make reading your blog a lot easier.

tatuaggi

February 6. 2010 09:43 PM

mccall idaho homes for sale

Hrmm that was weird, my comment got eaten. Anyway I wanted to say that it's nice to know that someone else also mentioned this as I had trouble finding the same info elsewhere. This was the first place that told me the answer. Thanks.

mccall idaho homes for sale

February 7. 2010 09:54 PM

free ipad

Nice to be visiting your blog again, it has been months for me. Well this article that i've been waited for so long. I need this article to complete my assignment in the college, and it has same topic with your article. Thanks, great share.

free ipad

February 8. 2010 10:27 PM

weight gain supplements

Excellent read, I just passed this onto a colleague who was doing a little research on that. And he actually bought me lunch because I found it for him smile So let me rephrase that: Thanks for lunch!

weight gain supplements

February 10. 2010 09:39 AM

eczema treatment

When I originally commented I clicked the "Notify me when new comments are added" checkbox and now each time a comment is added I get four emails with the same comment.
Is there any way you can remove me from that service?
Thanks!

eczema treatment

February 10. 2010 09:42 AM

juicer machine

How-do-you-do, just needed you to know I have added your site to my Google bookmarks because of your extraordinary blog layout. But seriously, I think your site has one of the freshest theme I've came across. It really helps make reading your blog a lot easier.

juicer machine

February 13. 2010 01:44 PM

Inglewood Garage Door Repair

Resources like the one you mentioned here will be very useful to me! I will post a link to this page on my blog. I am sure my visitors will find that very useful.

Inglewood Garage Door Repair

February 14. 2010 02:12 PM

kitchenaid professional mixer

I admire what you have done here. I like the part where you say you are doing this to give back but I would assume by all the comments that this is working for you as well.

kitchenaid professional mixer

February 15. 2010 03:14 AM

irt0421

You got a really useful blog I have been here reading for about an hour. I am a newbie and your success is very much an inspiration for me.

irt0421

February 22. 2010 06:05 AM

Mother's Day 2010

Just wanted to give you a shout from the valley of the sun, great information. Much appreciated.

Mother's Day 2010

February 22. 2010 07:39 AM

Mothers Day 2010

Me and my friend were arguing about an issue similar to this! Now I know that I was right. lol! Thanks for the information you post.

Mothers Day 2010

February 23. 2010 01:50 AM

Top rated treadmills reviewed

Hi. this is kind of an "unconventional" question , but have other visitors asked you how get the menu bar to look like you've got it? I also have a blog and am really looking to alter around the theme, however am scared to death to mess with it for fear of the search engines punishing me. I am very new to all of this ...so i am just not positive exactly how to try to to it all yet. I'll just keep working on it one day at a time.

Top rated treadmills reviewed

February 25. 2010 09:34 PM

electronic cigarette

Excellent read, I just passed this onto a colleague who was doing a little research on that. And he actually bought me lunch because I found it for him smile So let me rephrase that: Thanks for lunch!

electronic cigarette

February 28. 2010 04:47 AM

dr. britt borden

Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me.

dr. britt borden

March 2. 2010 12:14 AM

Forex

Couldn?t be written any better. Reading this post reminds me of my old room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thanks for sharing!

Forex

March 3. 2010 11:20 PM

Pay Per Call Marketing

Couldn?t be written any better. Reading this post reminds me of my old room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thanks for sharing!

Pay Per Call Marketing

March 5. 2010 01:58 PM

boards

Hi webmaster, commenters and everybody else !!! The blog was absolutely fantastic! Lots of great information and inspiration, both of which we all need!b Keep 'em coming... you all do such a great job at such Concepts... can't tell you how much I, for one appreciate all you do!

boards

March 7. 2010 03:10 PM

Contractor Accountants

I have recently started using the blogengine.net and I having some problems here? in your blog you stated that we need to enable write permissions on the App_Data folder...unfortunately I don't understand how to enable it.

Contractor Accountants

March 9. 2010 08:28 PM

traffic ultimatum review

Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me.

traffic ultimatum review

March 11. 2010 12:13 AM

portland dui

Well, this is my first visit to your blog! We are a group of volunteers and starting a new initiative in a community in the same niche. Your blog provided us valuable information to work on. You have done a marvellous job!

portland dui

March 15. 2010 07:50 AM

how to write a press release

Howdy, i read your blog occasionally and i own a similar one and i was just wondering if you get a lot of spam comments? If so how do you prevent it, any plugin or anything you can advise? I get so much lately it's driving me mad so any assistance is very much appreciated.

how to write a press release

March 16. 2010 09:52 AM

emekli sandıgı

This is a really good read for me, Must admit that you are one of the best bloggers I ever saw.Thanks for posting this informative article.

emekli sandıgı

March 16. 2010 04:32 PM

arac sorgulama

I admire the valuable information you offer in your articles. I will bookmark your blog and have my children check up here often. I am quite sure they will learn lots of new stuff here than anybody else!

arac sorgulama

March 16. 2010 05:33 PM

door handles

I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post

door handles

March 16. 2010 09:08 PM

pheromone perfume

The blog was absolutely fantastic! Lots of great information and inspiration, both of which we all need!

pheromone perfume

March 19. 2010 10:45 AM

fractions

Hey - nice blog, just looking around some blogs, seems a pretty nice platform you are using. I'm currently using Wordpress for a few of my sites but looking to change one of them over to a platform similar to yours as a trial run. Anything in particular you would recommend about it?

fractions

April 6. 2010 07:31 PM

hikaye

Thanks a lot for enjoying this beauty article with me. I am apreciating it very much! Looking forward to another great article. Good luck to the author! all the best!

hikaye

April 15. 2010 03:06 PM

kapadokya

Excellent post.I want to thank you for this informative read, I really appreciate sharing this great post. Keep up your work.

kapadokya

April 21. 2010 09:25 PM

plaka sorgulama

Thanks a lot for enjoying this beauty article with me. I am apreciating it very much! Looking forward to another great article. Good luck to the author! all the best!

plaka sorgulama

April 23. 2010 07:40 AM

rezzan kiraz

I just couldnt leave your website before saying that I really enjoyed the quality facts you provide to all your visitors. Would be back generally to check up on new stuff in you article!

rezzan kiraz

April 23. 2010 01:55 PM

L-Leucine

Valuable information! Looking forward to seeing your notes posted.

L-Leucine

April 23. 2010 07:56 PM

fallar fal bakma

Thanks a lot for enjoying this beauty article with me. I am apreciating it very much! Looking forward to another great article. Good luck to the author! all the best!

fallar fal bakma

April 26. 2010 08:54 PM

trafik ceza sorgulama

Hello,I love reading through your blog, I wanted to leave a little comment to support you and wish you a good continuation. Wishing you the best of luck for all your blogging efforts.

trafik ceza sorgulama

April 27. 2010 12:13 PM

Rapidshare

I\'m happy I found this blog, I couldnt discover any info on this subject matter prior to. I also run a site and if you want to ever serious in a little bit of guest writing for me if possible feel free to let me know, i\'m always look for people to check out my site. Please stop by and leave a comment sometime!

Rapidshare

April 28. 2010 08:48 AM

thy bilet fiyatları

Thank you for another great article. Where else could anyone get that kind of information in such a perfect way of writing? I have a presentation next week, and I am on the look for such information

thy bilet fiyatları

April 28. 2010 12:15 PM

dollar stores

An antartian walks into a bar down south around Christmastime; and there’s a little nativity scene on the bar. And the guy says, “That’s a nice nativity scene. But how come the three wise men are wearing firemen’s hats?” And the bartender says, “Well, it says right there in the Bible…. The three wise men came from a fire.”

dollar stores

May 4. 2010 09:37 AM

bağkur borc sorgulama

This is a really good read for me, Must admit that you are one of the best bloggers I ever saw.Thanks for posting this informative article.

bağkur borc sorgulama

May 5. 2010 09:26 PM

sgk

I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post

sgk

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading