serialize and deserialize

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Tony Johansson

    #1

    serialize and deserialize

    Hello!

    Assume I have a class called Product which is defined with the attribute
    [Serializable]
    I create a collection by using the generic class List in this way
    List<Productpro ducts = new List<Product>() ;

    product.Add(new Product(1, "some name 1",120));
    product.Add(new Product(1, "some name 2",130));
    product.Add(new Product(1, "some name 3",140));
    IFormatter serializer = new BinaryFormatter ();
    FileStream saveFile = new FileStream("Pro ducts.bin", FileMode.Create ,
    FileAccess.Writ e);
    serializer.Seri alize(saveFile, products);
    saveFile.Close( );

    Now to my question.
    When I want to deserialize do I then have to use the same kind of generic
    construction
    with List<Productsin the way shown below or can I use other construction.

    FileStream loadFile = new FileStream("Pro ducts.bin", FileMode.Open,
    FileAccess.Read );
    List<Productsav edProducts =
    serializer.Dese rialize((List<P roduct>)loadFil e);
    loadFile.Close( );

    My second question:
    I'm reading in a book and they say the following.
    "Some object don't serialize very well. They may require reference to local
    data that only exist
    while they are in memory, for example."
    What does this mean.

    //Tony




  • Marc Gravell

    #2
    Re: serialize and deserialize

    Well, move the cast and that is about right:

    List<Productsav edProducts = (List<Product>
    serializer.Dese rialize(loadFil e);

    Personally, I might be tempted to consider an xml-based serializer
    (such as XmlSerializer) since it will make fewer demands for specific
    assemblies, etc.

    Re some objects not serializing very well - this could mean references
    to non-serializable things like an SqlConnection, or it could mean
    things like unmanaged pointers / handles: these are essentially just
    numbers, but are useless at a different time, etc.

    Marc

    Comment

    Working...