Over a million developers have joined DZone.

C# Code To Test If An Object Is Serializable

DZone's Guide to

C# Code To Test If An Object Is Serializable

Free Resource
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

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


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


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

{{ parent.tldr }}

{{ parent.urlSource.name }}