VB.Net Event Implementation and Serialization Doesn’t Mix

OK, another rant on why I can’t stand the way VB.Net does things differently from the way C# does them (and usually for some sort of backward compatibility to VB6).  This time the weirdness came by way of trying to using binary serialization on a class that listens to events on a class that isn’t marked serializable.  Recently another developer on my team add events to a class that is marked serializable, and then added listeners to the UI class by marking the class with the WithEvents attribute.  He then added event handlers by way of the handles attribute on the sub.  The problem is that since VB.Net uses hidden multicast delegate fields when you use this VB-centric method of handling events, the binary serializer will try to serialize the UI class listening in on the events.  Prior to adding this bit of code, binary serialization worked fine.  Now with the new code, binary serialization fails with an error saying that the UI class isn’t marked serializable.  So I had to search around trying to figure out what broke, and how to fix it. 

Turns out the fix is pretty easy.  Just don’t use the VB-centric style of event handling.  Use AddHandlers instead of WithEvents and the Handles clause, and you avoid some of the serialization issues.  Once I fixed it, then I could Google it and it looks like Trev Hunter ran into a similar issue, and wrote an article on it.  I haven’t checked this out in .Net 2.0 beta 2, but I hope they fixed this issue.

I’m pulling this blog post.  I put it together a little too quickly, and it is very hard to read, and some of the comments were just wrong.  That’s what I get for jumping to conclusions, and not doing my usual thing, and creating the simplest project possible to test the bug I found.  When I get some more time, I’ll post a sample app, with the issues I have (although they are not as bad as I first thought, there are differences between what you can do with VB.Net and C#).

The preceding blog entry has been syndicated from the DonXML Demsak’s All Things Techie Blog.  Please post all comments on the original post. 

No Comments