Navaneeth K N
Navaneeth K N

Reputation: 15511

DataContractSerializer problem with events/delegate fields

On my WPF application, I am using DataContractSerializer to serialize object. I observed that it fails to serialize the types that has got an event or delegate declaration. Consider the following failing code:

[Serializable]
public abstract class BaseClass
{
    public string Name { get; set; }

    public event PropertyChangedEventHandler PropertyChanged;
}

public class DerivedClass : BaseClass
{
    public int Age { get; set; }
}


class Program
{
    static void Main(string[] args)
    {
        DerivedClass derivedClass = new DerivedClass {Name = "Test", Age = 10};
        derivedClass.PropertyChanged += (sender, eventArgs) => Console.WriteLine("hello");

        DataContractSerializer serializer  = new DataContractSerializer(typeof(DerivedClass));
        using(FileStream stream = new FileStream("c:\\test.txt", FileMode.Create, FileAccess.ReadWrite))
        {
            serializer.WriteObject(stream, derivedClass);
        }     
    }
}

This fails with message

Type 'System.DelegateSerializationHolder+DelegateEntry' with data contract name 'DelegateSerializationHolder.DelegateEntry:http://schemas.datacontract.org/2004/07/System' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.

I tried to add attributes like [DataMember(IsRequired = false)] on the event to indicate that it should not be serialized, but nothing worked.

Everything worked when I removed the [Serializable] attribute from the BaseClass. I am wondering why this behavior? Is it safe to avoid giving [Serializable] attribute?

.NET framework version : 3.5 SP1

Upvotes: 6

Views: 3683

Answers (1)

Kent Boogaart
Kent Boogaart

Reputation: 178760

[field:NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;

This tells the DataContractSerializer, "don't serialize the auto-generated EventHandlerList field for this event". Thus, any object instances attached to your event won't be considered part of the object graph being serialized.

Upvotes: 13

Related Questions