Dot NET
Dot NET

Reputation: 4897

Deserialization in Custom Collection Class

I've got a custom collection which adds functionality to the 'ArrayList' class.

Here's some code from the class:

    [Serializable]
    class Coll : ArrayList
    {

       public void Save(string path)
            {
                BinaryFormatter formatter = new BinaryFormatter();
                FileStream fsOut = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
                formatter.Serialize(fsOut, this);
                fsOut.Dispose();
            }
    }

I'm now trying to deserialize a file, and fill the collection with the contents of the file. Basically the opposite of my Save(string path) method.

This is what I've got so far:

public void Read(string path)
            {
                BinaryFormatter formatter = new BinaryFormatter();
                FileStream fsIn = new FileStream(path, FileMode.Open, FileAccess.Read);
                formatter.Deserialize(fsIn);
                fsIn.Dispose();
            }

How should I go about populating the collection with the contents which has been deserialized?

Upvotes: 0

Views: 203

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062945

BinaryFormatter doesn't support serialising into an existing object. You could deserialize it into a new list - just make it a static method and return the value.

Other thoughts:

  • don't use ArrayList unless you are in .net 1.1: List<T> would be preferable
  • no need to subclass; an extension method would suffice
  • I don't recommend BinaryFormatter for this... Or anything else really

Upvotes: 2

Yogu
Yogu

Reputation: 9445

The method BinaryFormatter.Deserialize() creates a new object, initializes it with the data from the stream and returns it. Therefore, you should use the return value and use it as the new ArrayList object. The Read method thus goes into a static method, or -- as diggingforfire suggested -- into another class.

Upvotes: 1

Related Questions