Search code examples
c#.netserializationpersistenceobject-oriented-database

The best way to store class instances to a file/database


What is the best way to store instances of a class to file/database?

We have a base class called Command and loads of derived classes. Users create instances of these classes by adding commands to a graphical designer where they can configure them. (Set the properties).

We then need a way to store these "commands" to a file without losing any information.

One idea was to use db4o, but the GPL license is not acceptable for this project.

Any suggestions or code samples?

Update:

(In order to "de-blurryfie" my question :p)

The generated code might look something like:

    command[i++] = new DelayInSecondsCommand(2);
    command[i++] = new DaliRequestCommand(1, false, 254);
    command[i++] = new DaliRequestCommand(2, false, 254);
    command[i++] = new DaliRequestCommand(3, false, 254);
    command[i++] = new WaitInSecondsCommand(2);             
    command[i++] = new DaliRequestCommand(1, false, 0);
    command[i++] = new DaliRequestCommand(2, false, 0);
    command[i++] = new DaliRequestCommand(3, false, 0);
    command[i++] = new JumpCommand(0);

But then with loads of different commands.

I know it's possible with .NET serialization, altough I've never used it before, but I was wondering if there are better alternatives, like I said db4o seems nice but the license doesn't fit the project.

Update 2:

Thank you for the replies. I'll probably go with the serialization solution now, but I'll look into the other options as well. F.Y.I. data is stored in a SQL Compact database.


Solution

  • serialization does the trick! Serialization is nothing more than converting an object or a connected graph of objects into a stream of bytes (in order to persist the current state of the object). This can be a binary stream, XML or whatever. You don't have to do this conversion by your own since .Net has great support for serialization. Once you serialized an object, you are free to store this data to a file or database. Likewise, a stream of bytes representing a serialized object can be deserialized into an object which will have the same state as the original one.

    Btw: Once you have a serialized stream of bytes, you can apply some more functions on it, e.g. compression or encryption.