serialize and deserialize

T

Tony Johansson

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<Product> products = 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("Products.bin", FileMode.Create,
FileAccess.Write);
serializer.Serialize(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<Products> in the way shown below or can I use other construction.

FileStream loadFile = new FileStream("Products.bin", FileMode.Open,
FileAccess.Read);
List<Product> savedProducts =
serializer.Deserialize((List<Product>)loadFile);
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
 
M

Marc Gravell

Well, move the cast and that is about right:

List<Product> savedProducts = (List<Product>
serializer.Deserialize(loadFile);

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top