Over a million developers have joined DZone.

C# Code To Test If An Object Is Serializable

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(Stream stream)
    IFormatter formatter = new BinaryFormatter();
    stream.Position = 0;
    return (T)formatter.Deserialize(stream);

public static T CloneBySerialization(T source)
    return Deserialize(Serialize(source));

public static void AssertRoundTripSerializationIsPossible(T source)
{   // assumes T implements Equals
    T clone = CloneBySerialization(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");

public void ClassShouldBeSeralizable()
    Foo original = new Foo("bar");

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}