RSS 2.0
# Wednesday, September 02, 2009

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 :).

Wednesday, September 02, 2009 11:11:22 PM (W. Europe Daylight Time, UTC+02:00)  #    Comments [0] -
.NET | Development | English | Services
Sign In

Archive
<September 2009>
SunMonTueWedThuFriSat
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910
About
This is the blog of Michiel van Otegem, a Senior Software Architect with Sogeti Netherlands, and author of several books and numerous articles on (ASP).NET, XML, and related technologies.
Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2012
Michiel van Otegem
All Content © 2012, Michiel van Otegem
DasBlog theme 'Business' created by Christoph De Baene (delarou)