What are the drawbacks of marking a class as serializable?
I need to save my asp.net session in a db and it requires that the objects in the session are serializable.
Make sense.
But turns out that all I had to do was decorate that class with the [Serializable]
attribute and it worked, so that means .NET already has the underlying infrastructure to make classes serializable. So why can't it just do it by default?
What's the need to mark it as such?
The Serializable interface does not offer fine-grained control over object access - although you can somewhat circumvent this issue by implementing the complex Externalizable interface, instead.
Some of its primary advantages are: Used for marshaling (traveling the state of an object on the network) To persist or save an object's state. JVM independent.
The easiest way to make a class serializable is to mark it with the SerializableAttribute as follows. The following code example shows how an instance of this class can be serialized to a file. MyObject obj = new MyObject(); obj. n1 = 1; obj.
It is not necessary to use this attribute if a given type implements the System. Runtime. Serialization. ISerializable interface, which indicates that a class provides its own methods for serialization.
So why can't it just do it by default?
Automatic serialization/deserialization might not suffice for the object. For example, the object might contain a field that holds the name of a local file, a pointer to memory, an index into a shared array, etc. While the system could typically serialize these raw values without trouble, deserialization could easily result in something that is not usable. In general, it is impossible for the system to figure this out on its own. By requiring you to mark the class with Serializable
, you indicate that you have taken these considerations into account.
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