views:

132

answers:

1

I'm attempting to Serialize my custom collection UserDataCollection, made out of UserData objects. I wondered when implementing Serialization, does the actual object (UserData) also need have the attribute [Serializable] and inherit from the ISerializable interface?

I want to serialize each object (UserData) in the collection, all it's properties and variables.

I have this at the moment:

public class UserData : IEquatable<UserData>, IUser
{
/// some properties methods
}

    [Serializable()]
    class UserDataCollection : IEnumerable<UserData>, ISerializable
    {
        static List<UserData> Collection = new List<UserData>();
        IUser current;

        #region Properties
        public UserData Current
        {
            get 
            { 
                return (UserData)current; 
            }

            set
            {
                current = value;
            }
        }
        #endregion


        #region Constructors
        public UserDataCollection( IUser userdata )
        {
            this.current = userdata;
        }

        /// <summary>
        /// Deserialization Constructor
        /// </summary>
        /// <param name="SerializationInfo">This object holds a name-value pair for the             properties to be serialized</param>
        /// <param name="item"></param>
        public UserDataCollection(SerializationInfo serializationInfo, StreamingContext ctxt)
        {
            Current = (UserData)serializationInfo.GetValue("UserData", typeof(UserData)); <-- Can I just do this on the UserData object property or does it itself  also need to implement ISerializable?
        }
        #endregion

//more methods here...
}

The collection will be serialized using binary serialization.

+2  A: 

Yes, your UserData class should be marked as Serializable. It does not have to explicitly inherit from ISerializable, but if you want to customize the serialization then of course you can.

From SerializableAttribute:

Apply the SerializableAttribute attribute to a type to indicate that instances of this type can be serialized. The common language runtime throws SerializationException if any type in the graph of objects being serialized does not have the SerializableAttribute attribute applied.

womp