views:

32

answers:

1

Surprised this question has not been asked yet here, but here goes:

Serialization in VB.NET is a bit of a pain. If you use the standard Serializable() attribute, and attempt to serialize a class that has events which are attached to handlers, it will attempt to serialize the handlers as well.

Coming from a C# background I am not used to dealing with this problem, and the best solution I can find is using a class off of CodeProject.

However I'd rather not change the object inheritance structure for this idea.

What is the standard way to do Serialization of classes created in VB.NET?

I have heard of removing all handlers, serializing, then re-adding all handlers, but couldn't that lead to events firing and not getting handled?

+1  A: 

In C#, the solution is to apply the NonSerializedAttribute to the event's backing field, using the field: prefix on the attribute. Unfortunately, VB doesn't support the field: trick, so you need to make the event's backing field explicit, and apply NonSerializedAttribute to that. Rocky Lhotka has sample code for this.

Unfortunately it does look rather verbose and tedious, since now you have to spell out the add, remove and raise methods for each event.

itowlson