I am using C# 2.0 with Nunit Test. I have some object that needs to be serialized. These objects are quite complex (inheritance at different levels and contains a lot of objects, events and delegates).
How can I create a Unit Test to be sure that my object is safely serializable?
You can determine whether an object is serializable at run time by retrieving the value of the IsSerializable property of a Type object that represents that object's type.
If you are curious to know if a Java Standard Class is serializable or not, check the documentation for the class. The test is simple: If the class implements java. io. Serializable, then it is serializable; otherwise, it's not.
Q6) What happens if the object to be serialized includes the references to other serializable objects? Ans) If the object to be serialized includes references to the other objects, then all those object's state also will be saved as the part of the serialized state of the object in question.
Try marking the field with [NonSerialized()] attribute. This will tell the serializer to ignore the field.
Here is a generic way:
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 Clone<T>(object source) { return Deserialize<T>(Serialize(source)); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With