Monday, May 31, 2004
« Services, Objects and People, Oh my! | Main | Dispose your Command objects! »

A few weeks ago I posted an entry about a solution to today's problem with serializing objects that declare events. It was pointed out that there's a better way to handle the list of delegates, and so here's a better version of the code.

  _
  Private mNonSerializable As EventHandler
  Private mSerializable As EventHandler

  Public Custom Event NameChanged As System.ComponentModel.EventHandler
    AddHandler(ByVal value As System.ComponentModel.EventHandler)
      If value.Target.GetType.IsSerializable Then
        mSerializable = CType([Delegate].Combine(mSerializable, value), EventHandler)

      Else
        mNonSerializable = CType([Delegate].Combine(mNonSerializable, value), EventHandler)
      End If
    End AddHandler

    RemoveHandler(ByVal value As System.ComponentModel.EventHandler)
      If value.Target.GetType.IsSerializable Then
        mSerializable = CType([Delegate].Remove(mSerializable, value), EventHandler)

      Else
        mNonSerializable = CType([Delegate].Remove(mNonSerializable, value), EventHandler)
      End If
    End RemoveHandler

    RaiseEvent(ByVal sender As Object, ByVal e As System.ComponentModel.EventArgs)
      If mNonSerializable IsNot Nothing Then mNonSerializable(sender, e)
      If mSerializable IsNot Nothing Then mSerializable(sender, e)
    End RaiseEvent
  End Event

Tuesday, July 11, 2006 7:29:48 PM (Central Standard Time, UTC-06:00)
Hey, thanks for the post. I found it helpful. There is a great lack of documentation on Custom Events.
Lance Fisher
Thursday, August 10, 2006 9:07:18 AM (Central Standard Time, UTC-06:00)
Hi Rocky:

Shouldn't

Private mNonSerializable As EventHandler

be

[NonSerialized()] Private mNonSerializable As EventHandler

I used C#'s attribute characters above 'cos VB's are rejected by ASP.NET

- Taiwo
Taiwo Ayedun
Thursday, August 10, 2006 9:14:02 AM (Central Standard Time, UTC-06:00)
Yes, that's true. I think it is there actually (see that dangling line continuation), but the blog software ate it because of the angle brackets or something...
Comments are closed.