-
June 9th, 2009, 05:48 AM
#1
Binary Serialization
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
-
June 9th, 2009, 12:17 PM
#2
Re: Binary Serialization
You don't have to implement ISerializable unless you need to make custom serialization.
You just need to mark the class as serializable:
Code:
[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:
Code:
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, although I don't agree to many points.
-
June 9th, 2009, 02:32 PM
#3
Re: Binary Serialization
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
-
June 9th, 2009, 03:32 PM
#4
Re: Binary Serialization
Originally Posted by Trinominal
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 for a discussion about this issue.
-
June 9th, 2009, 04:49 PM
#5
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|