Click to See Complete Forum and Search --> : Binary Serialization


Trinominal
June 9th, 2009, 05:48 AM
Hi,

I want to serialize an object model into a binary file.
I saw that it can be done using the BinaryFormatter class, but then I need the objects in my object model to inherit the ISerializable interface and implement it, and I also afraid that because this is more or less a generic method of serializing, that there might be an impact on the performance.

1. Are you aware of any performance issues with this method ?
2. Are there any other methods of serializing objects into binary files, which are custom (i.e., I write the persistence code myself, without inherit the ISerializable interface) ?

Regards

hspc
June 9th, 2009, 12:17 PM
You don't have to implement ISerializable unless you need to make custom serialization.
You just need to mark the class as serializable:
[Serializable]
public class MyClass
{
string _name;
int _value;

public string Name
{
get { return _name; }
set { _name = value; }
}
public int Value
{
get { return _value; }
set { _value = value; }
}

}

then use BinaryFormatter:

BinaryFormatter b = new BinaryFormatter();

FileStream stream = File.OpenWrite("c:\\file.dat");

MyClass c= new MyClass();
c.Name="test";
c.Value = 5;

b.Serialize(stream,c);

stream.Close();

stream = File.OpenRead("c:\\file.dat");

c= b.Deserialize(stream) as MyClass;

stream.Close();

There are different opinions regarding using serialization, take a look at this article (http://www.codeproject.com/KB/dotnet/noserialise.aspx), although I don't agree to many points.

Trinominal
June 9th, 2009, 02:32 PM
Thanks.

Are you recommanding just using BinaryWriter class to write to the file, and a BinaryReader to read from it, as a custom serializer?

Regards

hspc
June 9th, 2009, 03:32 PM
Are you recommanding just using BinaryWriter class to write to the file, and a BinaryReader to read from it, as a custom serializer?
It's totally dependent on your situation, I think the factors you need to take into consideration are:


Performance. What is he type of your application (server application / desktop). Why and how frequently do you serialize and deserialize?
Version compatibility, check what will happen when you change the class or assembly version. check this link (http://stackoverflow.com/questions/505611/binary-deserialization-with-different-assembly-version) for a discussion about this issue.

Trinominal
June 9th, 2009, 04:49 PM
Thanks a lot.