Developers have to 'opt in' for making classes serializable by explicitly using SerializableAttribute
. What could go wrong if classes were serializable by default?
Serialization allows the developer to save the state of an object and re-create it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions such as: Sending the object to a remote application by using a web service.
But then I researched and found that "string is serializable by default" is only true in . NET framework because string definition is decorated with the Serializable attribute in . NET; whereas, in . NET Core string definition is not decorated with the Serializable attribute.
By default, classes are not serializable unless they are marked with SerializableAttribute. During the serialization process all the public and private fields of a class are serialized by default. Fields marked with NonSerializedAttribute are excluded during serialization.
I would assume that classes are not serializable by default because there's no guarantee that a dump of the object's state to a stream using Reflection even makes sense. What if your object holds an open connection to a database or communication port? Whenever a new object was constructed by deserializing an instance of the previous object, you would end up with a useless object.
Plus, you have to consider that whenever a class is serializable, the runtime insists that all of its member variables be serializable as well, unless they are explicitly marked otherwise. It's much easier to make serializability an opt in functionality for developers, rather than forcing them to opt out certain members.
And finally, you might have certain fields in your class that contain private or sensitive information. Having to explicitly mark classes as serializable ensures that you don't accidentally expose the details of something (whether it be the data or your implementation) to the world that you didn't mean to be public.
Serializable classes imply that they have some kind of state that can be written to an external location and read again. For a lot of classes that doesn't make any sense at all - what kind of state does a Thread have, that you could successfully serialize?
It's a little bit philosophical but by convention the default type of a class is not serializable, unless you explicitely define "this class can be serialized".
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