views:

308

answers:

3

I need to avoid serializing an Event class member because when the event is handled by an object that is not marked as Serializable the serialization will fail.

I tried using the NonSerialized attribute on the Event class member but it fails to compile with the following error:

<NonSerialized()> Public Event PropertyValueChanged()

results in:

Attribute 'NonSerializedAttribute' cannot be applied to 'PropertyValueChanged' because the attribute is not valid on this declaration type.

Public Event PropertyValueChanged() ' compiles but needs the extra handling described below

Is there another way to avoid serializing Event members?

This is not a problem if the event is not handled and I can work around it by cloning the objects (and ignoring the event) before serializing them. Just wondering if there is a better way.

Thanks.

+5  A: 

In C# you can do this as below, so I hope this translates identically to VB.

Note this only applies to field-like events (i.e. where you don't have your own add/remove):

[field: NonSerialized]
public event EventType EventName;

Otherwise something like:

[NonSerialized]
EventType backingField;
public event EventType {
    add { backingField += value; }
    remove { backingField -= value; }
}
Marc Gravell
+1 I should have known, that there was going to be no way to beat you to answering this question.
Kevin
Well I learned something new :) Nice solution.
NebuSoft
Unfortunately neither option translates to VB...
Paul Sasik
Link to VB.NET discussion and possible workaround: http://www.lhotka.net/WeBlog/CommentView.aspx?guid=776f44e8-aaec-4845-b649-e0d840e6de2c
Paul Sasik
I implemented the solution in its entire per the link provided above and the serialization still fails. Giving up... My ICloneable workaround will do.
Paul Sasik
+1 Good Stuff :)
SwDevMan81
A: 

It isn't working because the compiler actually generates a backing field for the event. To enable it, just prefix your attribute with field:

[field: NonSerialized]
public event EventHandler PropertyValueChanged;
Abe Heidebrecht
This doesn't work for VB.NET for some reason.
Paul Sasik
A: 

How I've done it in the past for projects is implement the IXmlSerializable interface and control my serialization manually. I find this makes serializing GUI based controls (with lots of events) much easier.

IXmlSerializable

NebuSoft
`IXmlSerializable` doesn't apply to binary serialization. It would be `ISerializable`, which is very different.
Marc Gravell
I missed where he tagged it for Binary. My mistake, for some reason I assumed he was asking for Xml.
NebuSoft