Stephan Jennewein
Stephan Jennewein

Reputation: 313

Serialization of a class with events

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?

Upvotes: 22

Views: 12883

Answers (4)

Johan Larsson
Johan Larsson

Reputation: 17590

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.

Upvotes: 33

TomDestry
TomDestry

Reputation: 3399

The NonSerialized attribute is only available for fields, so to use it you have to adjust your code to use fields.

Try creating your event like this:

[NonSerialized]
private ChangedEventHandler _changed;
public event ChangedEventHandler Changed
{
    add { _changed += value; }
    remove { _changed -= value; }
}

Then in the value property use the field, not the property:

public double value
{
    get { return _value; }
    set 
    {
        _value = value;
        if (_changed != null)
        {
            _changed(this, EventArgs.Empty);
        }
    }
}
private double _value = 0;

Upvotes: 13

cdel
cdel

Reputation: 706

Use the [NonSerialized] attribute to avoid serialization of the event.

Upvotes: 1

Matt B
Matt B

Reputation: 8653

Either mark StepPulseBlaster as serializable or use the XmlIgnore attribute to prevent Changed from being serialized.

Upvotes: 1

Related Questions