In my WPF application, I use a DataContractSerializer to serialize an object. I noticed that it cannot serialize types that have an event or delegate declaration. Consider the following error 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 the data contract name 'DelegateSerializationHolder.DelegateEntry: http://schemas.datacontract.org/2004/07/System ' is not expected. Add any types, not statically known, to the list of known types - for example, using the KnownTypeAttribute attribute or adding them to the list of known types passed to the DataContractSerializer.
I tried adding attributes such as [DataMember(IsRequired = false)] to the event to indicate that it should not be serialized, but nothing works.
Everything worked when I removed the [Serializable] attribute from BaseClass . I wonder why this behavior? Is it safe to avoid using the [Serializable] attribute?
.NET Platform Version: 3.5 SP1
Navaneeth KN
source share