Home Contact

X

Coder, not artist.

News

Current archive is at: http://cskardon.wordpress.com/ - I aim to move it all soon! All code on here is free, but as a consequence it's up to you to check it, ha! If you have any questions, feel free to email: cskardon -- @ -- xclave dot co dot uk I'm sure you can decrypt the address there!

Twitter












Archives

Post Categories

Image Galleries

Syndication:

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;
    }
}

Feedback

# re: Quick Serialization / Deserialization Helper Method

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 );
}
9/1/2008 5:38 PM | Eddie Velasquez

# re: Quick Serialization / Deserialization Helper Method

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 9/2/2008 8:16 AM | Chris

# re: Quick Serialization / Deserialization Helper Method

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. 9/7/2008 11:10 PM | Eddie Velasquez

# re: Quick Serialization / Deserialization Helper Method

I've updated the code to use 'usings'... :) 9/8/2008 2:34 PM | Chris

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: