views:

121

answers:

1

I have this code for serializing my custom collection of UserData Objects. However the current property only represents the item currently being used in the collection, so it only serializes that one object.

I want all the objects serialized in my collection, how would I go about that in the GetObjectData implementation of my Collection?

        public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
        {
            // Add the userdata object to SerializationInfo object
                info.AddValue("UserData", current);
        }

this is my deserialization constructor, I'm not sure this will then deserialize each object in the collection either.

public UserDataCollection(SerializationInfo serializationInfo, StreamingContext ctxt)
        {
            UserData data = (UserData)serializationInfo.GetValue("UserData", typeof(UserData));
              // Add to objects existing collection
            this.Add(data);
        }
+1  A: 

How are you holding your objects behind the scenes? Do you have a List<T> field somewhere? Just serialize / deserialize that, and let it worry about it. To be honest, this should just happen if you mark the custom collection wrapper as [Serializable] and mark any unnecessary fields (such as current) as [NonSerialized] (i.e. without you having to implement ISerializable).

Note that in most scenarios I tend to advise against BinaryFormatter; it is OK for sending short-lived (transient) messages, but I don't advise using it for storage purposes (in a file or in a database); you can get lots of versioning issues trying to deserialize at a later date.

Marc Gravell
Thanks Mark! I wondered, what kind of Serialization do you then recommend? XML?
Tony
It depends what you need. XmlSerializer / DataContractSerializer are ood for xml; json.net is another text-based option. For binary I recommend protobuf-net, but I kinda would... (but it is free...)
Marc Gravell