Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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
    
     (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");
}

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

      
     
    
   
  
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

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.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}