2

My task was to serialize and deserialize an object.

I want to know:

  • Whether my object is serialized in the way I'm doing it
  • How I get to know that my object is being serialized or deserialized

Instead of passing the object in the Serialize Method, I am passing object.properties. Does this affect it in any way?

FileStream fs = new FileStream(@"D:\Rough Work\Serialization\Serialization\bin\Debug\Log.txt",FileMode.OpenOrCreate);
Laptop obj = new Laptop();
obj.Model = 2;
obj.SerialNumber = 4;
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, obj.Model);
formatter.Serialize(fs, obj.SerialNumber);

[Serializable]
class Laptop
{
    public int Model;
    public int SerialNumber;
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Abid Ali
  • 1,731
  • 8
  • 26
  • 62

3 Answers3

5
  • If you can successfully deserialize an object then you serialized it correctly.
  • You don't need to serialize the properties individually. You can just serialize the entire object and deserialize it the same way.

    using (var fs = new FileStream(@"D:\Rough Work\Serialization\Serialization\bin\Debug\Log.txt",FileMode.OpenOrCreate))
    {
        var formatter = new BinaryFormatter();
        formatter.Serialize(fs, obj);
    }
    
    using (var fs = new FileStream(@"D:\Rough Work\Serialization\Serialization\bin\Debug\Log.txt",FileMode.OpenOrCreate))
    {
        var formatter = new BinaryFormatter();
        obj = formatter.Deserialize(fs) as Laptop;
    }
    

If your question is how would Laptop class know that it is being serialized then you might want to implement ISerializable interface.

See BinaryFormatter.Deserialize

Muhammad Hasan Khan
  • 34,648
  • 16
  • 88
  • 131
  • well, this was the question in my Mid-Term paper. I`ve alse deserialized an object this way by passing obj.Properties in desirialize method. – Abid Ali Nov 22 '11 at 10:45
  • @AbidAli if you serialize the properties then you also have to deserialize them same way. The serialized file in both cases is different. – Muhammad Hasan Khan Nov 22 '11 at 10:55
0

You can convert to serialised method to a string and output it to the debug window

Joseph Le Brech
  • 6,541
  • 11
  • 49
  • 84
0

I want to know: Whether my object is serialized in the way I'm doing it

Then you can use xml serialization, that way you can check your serialized object since it will be in human-readable form.

0lukasz0
  • 3,155
  • 1
  • 24
  • 40