DataContractSerializer and interfaces

I was working on this little app I wrote a while ago and wanted to add some features requiring (de)serialization. So, I took the original class and made it a DataContract so I could use it with the DataContractSerializer. The class then looked more or less like this:

[DataContract]
public class MyClass
{
List<Trip> m_Items = new List<Item>();

[DataMember]
public IList<Item> Items
{
get { return m_Items; }
}
}


Serialization went fine, but when I tried to deserialize the same object, I got a null reference exception. Of course you say, you should have added a method tied to de OnDeserializing event, because the constructor of the object doesn’t work and hence the m_Items field is never initialized. The code I added to solve this looked like this:

[OnDeserializing]
protected void Init(StreamingContext context)
{
m_Items = new List<Item>();
}

To my surprise I still got the same exception. I finally figured out that the problem was the type of Items. It is was an IList<> instead of a List<>. To avoid tying a class to a specific implementation of a list, I usually use an interface, which is good practice in most cases… however, not when you want to do deserialization :).

Leave a Reply

Your email address will not be published. Required fields are marked *