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
This tells the
DataContractSerializer, “don’t serialize the auto-generatedEventHandlerListfield for this event”. Thus, any object instances attached to your event won’t be considered part of the object graph being serialized.