Why does the target method of PropertyChanged needs to be public to be serialized?

Why does the target method of PropertyChanged needs to be public to be serialized?

Old forum URL: forums.lhotka.net/forums/t/6241.aspx


mikemir8 posted on Thursday, January 22, 2009

Just curious about this, but why does the target method of eventhandlers like PropertyChanged and Saved need to be public to be serialized?

- Miguel

ajj3085 replied on Friday, January 23, 2009

Not sure I follow..

rsbaker0 replied on Friday, January 23, 2009

^^^

This strikes me as odd also. My experience is that event *handlers* are rarely public.

What symptoms are you experiencing that suggest these need to be public?

mikemir8 replied on Friday, January 23, 2009

I have a static class that listens for the PropertyChanged event of certain objects (following the Observer pattern), and I started noticing that after saving the object with autoclone enabled, the events were no longer hooked up. Of course I had my event handlers as private.

So I went and looked at the implementation of PropertyChanged in BindableBase:

    public event PropertyChangedEventHandler PropertyChanged
    {
      add
      {
        if (value.Method.IsPublic &&
           (value.Method.DeclaringType.IsSerializable ||
            value.Method.IsStatic))
          _serializableHandlers = (PropertyChangedEventHandler)
            System.Delegate.Combine(_serializableHandlers, value);
        else
          _nonSerializableHandlers = (PropertyChangedEventHandler)
            System.Delegate.Combine(_nonSerializableHandlers, value);
      }


Of course, after a serialization, only serializable handlers will be re-hooked up automatically. What I don't get (not saying it's wrong, just don't get it) is why the target method needs to be public to be added to the serializable handlers.

- Miguel

RockfordLhotka replied on Friday, January 23, 2009

I honestly don't remember. This was a pattern I developed around 2003 or 2004 to deal with the event serialization issues, and I did a lot of research on it then - but that was 4-5 years ago :(

If you can establish that the BinaryFormatter and NDCS will reestablish hookups to non-public event handlers I'll certainly consider changing the code.

mikemir8 replied on Friday, January 23, 2009

Thanks for the answer Rocky. For now, I guess I'll leave it as is since it's not really causing me a problem. Besides, my experience says that things so specific usually have a good reason... even if sometimes we forget =)

Maybe later I can come back to this and do some and play around a little bit.

- Miguel

RockfordLhotka replied on Friday, January 23, 2009

I've actually given serious consideration to simplifying this code, and never trying to maintain the event hookup.

I believe Microsoft's more recent event implementations follow that pattern, where they simply leave all events unhooked on deserialization.

Copyright (c) Marimer LLC