thomas
thomas

Reputation: 164

How to serialize a custom EventHandler

Good morning,

I got a class DirObserver with a custom event:

public EventHandler<FileDetectedEventArgs> NewFileDetected;

I try to serialize this class in a other class with:

private XmlSerializer serializer = new XmlSerializer(typeof(List<DirObserver>));

But i get an exception: FileDetectedEventArgs cannot be serialized because it does not have a parameterless constructor.

But the FileDetectedEventArgs-Class have a parameterless constructor:

public class FileDetectedEventArgs : EventArgs
{
    public String Source { get; set; }
    public String Destination { get; set; }
    public String FullName { get; set; }

    public FileDetectedEventArgs(String source, String destination, String fullName)
    {
        this.Source = source;
        this.Destination = destination;
        this.FullName = fullName;
    }

    public FileDetectedEventArgs() { }
} 

Nevertheless the exception will be raised. Whats the problem here?

Thanks and greets Thomas

Upvotes: 2

Views: 2158

Answers (2)

Maarten
Maarten

Reputation: 22955

Eventhandlers are not made to be serialized. If you look into the inner exceptions of your exception, you will see it is the EventHandler class which does not have a parameterless constructor; it is a delegate.

You probably want to exclude the eventhandler from serialization; add an XmlIgnore attribute.

Update

I missed the missing event keyword as mentioned by @Reniuz. Serialization works with that correction. Still, serializing eventhandlers in general is a bad idea I think.

Upvotes: 1

Renatas M.
Renatas M.

Reputation: 11820

Change

public EventHandler<FileDetectedEventArgs> NewFileDetected;

to

public event EventHandler<FileDetectedEventArgs> NewFileDetected;

Upvotes: 2

Related Questions