DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Jason has posted 22 posts at DZone. View Full User Profile

C# Code To Test If An Object Is Serializable

08.02.2011
| 3973 views |
  • submit to reddit
        The code below contains utility methods and an example test method to check if a class is truly serializable by cloning it using serialization then comparing the original to the clone.

public static Stream Serialize(object source)
{
    IFormatter formatter = new BinaryFormatter();
    Stream stream = new MemoryStream();
    formatter.Serialize(stream, source);
    return stream;
}

public static T Deserialize<T>(Stream stream)
{
    IFormatter formatter = new BinaryFormatter();
    stream.Position = 0;
    return (T)formatter.Deserialize(stream);
}

public static T CloneBySerialization<T>(T source)
{
    return Deserialize<T>(Serialize(source));
}

public static void AssertRoundTripSerializationIsPossible<T>(T source)
{   // assumes T implements Equals
    T clone = CloneBySerialization<T>(source);
    Assert.AreEqual(source, clone, "Failed round-trip serialization, clone not equal to source");
    Assert.IsFalse(ReferenceEquals(source, clone), "Failed round-trip serialization, clone points to souce");
}

[TestMethod]
public void ClassShouldBeSeralizable()
{
    Foo original = new Foo("bar");
    AssertRoundTripSerializationIsPossible(original);
}