Quick Serialization / Deserialization Helper Method

After discovering some pretty significant serializaton issues in the code base, and approximately 0% testing of the implementation of ISerializable, I've been spending the last couple of days writing tests for the serialization... I've been using the following code to do the serialization, easy to use:

MyObject m = new MyObject("Test");
Assert.IsTrue( m.Equals( Serialization.SerializeAndDeserialize( m ) ) );

Of course, this uses the 'Serialization' class, which is defined below!

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
 
/// <summary>Class to aid the serialization / deserialization of objects in unit tests.</summary>
public static class Serialization
{
    /// <summary>Serializes and deserializes the specified object.</summary>
    /// <typeparam name="T">The type of object to serialize / deserialize.</typeparam>
    /// <param name="toSerialize">The actual object to serialize / deserialize.</param>
    /// <param name="filename">The location to serialize the object to.</param>
    /// <returns>The deserialized object.</returns>
    public static T SerializeAndDeserialize<T>( T toSerialize, string filename )
    {
        // Serialization
        using(Stream sStream = new FileStream( filename, FileMode.Create ))
            new BinaryFormatter().Serialize( sStream, toSerialize );
 
        // Deserialization
        T newObj;
        using(Stream dStream = new FileStream( filename, FileMode.Open ))
            newObj = (T) new BinaryFormatter().Deserialize( dStream );
        
        //Delete files
        File.Delete( filename );
 
        return newObj;
    }
}

Print | posted @ Monday, September 1, 2008 11:14 AM

Comments on this entry:

Gravatar # re: Quick Serialization / Deserialization Helper Method
by Eddie Velasquez at 9/1/2008 5:38 PM

You are missing several using statements. In case of exceptions you could leak "filename" and/or leak "sStream" and/or "dStream" until their finalizers run.
Off the top of my head; I didn't actually compile this:

try
{
// Serialization
using( Stream sStream = new FileStream( filename, FileMode.Create ) )
{
IFormatter sFormatter = new BinaryFormatter();
sFormatter.Serialize( sStream, toSerialize );
}

// Deserialization
using( Stream dStream = new FileStream( filename, FileMode.Open ) }
{
IFormatter dFormatter = new BinaryFormatter();
T newObj = (T) dFormatter.Deserialize( dStream );
}
}
finally
{
File.Delete( filename );
}
Gravatar # re: Quick Serialization / Deserialization Helper Method
by Chris at 9/2/2008 8:16 AM

Hi Eddie, thanks for the comments, to answer your points quickly:

* Not really missing 'using' - just different ways of doing things. I close the streams after each use, admittedly I could have done this (should have!) in a finally block, which (lets face it) is what the using gives us for free!

* Pretty much the same with the File.Delete, though I'm less worried about this, as I just overwrite it anyhow next time I run the method!

Cheers and thanks for commenting, I'll probably update the code shortly :)

Chris
Gravatar # re: Quick Serialization / Deserialization Helper Method
by Eddie Velasquez at 9/7/2008 11:10 PM

Well, I should've been clearer. It's more than just different ways of doing things; by using a using statement (no pun intended!) you will ensure that the streams will be disposed even in the case of an exception. You can indeed use a try/finally block instead of the using statement but; in my opinion, it's better to use using unless you need to use a catch block too; in which case try/catch/finally will be a better option.
Gravatar # re: Quick Serialization / Deserialization Helper Method
by Chris at 9/8/2008 2:34 PM

I've updated the code to use 'usings'... :)
Post A Comment
Title:
Name:
Email:
Comment:
Verification: