Serialization of a class with events

Stephan Jennewein picture Stephan Jennewein · May 30, 2012 · Viewed 10.8k times · Source

I have a Class like this:

public delegate void ChangedEventHandler(object sender, EventArgs e);
[Serializable]
public class valueDouble
{
    public event ChangedEventHandler Changed;
    public double value
    {
        get { return _value; }
        set 
        {
            _value = value;
            if (Changed != null)
            {
                Changed(this, EventArgs.Empty);
            }
        }
    }
    private double _value = 0;
}

I also have another Class (StepPulseblaster) which is not serializable and adds an Event Handler

valDouble.Changed += new ChangedEventHandler(sc_PropertyChanged);

When i try to serialize the valueDouble Class, there will be an error:

The Type StepPulseblaster is not marked as serializable

When i comment the line

valDouble.Changed += ...

there will be no error any more.

How can i serialize a class which has some events connected?

Answer

Johan Larsson picture Johan Larsson · May 27, 2015

You should do:

[field: NonSerialized]
public event ChangedEventHandler Changed;

As described in the MSDN:

To apply the NonSerializedAttribute class to an event, set the attribute location to field.