Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why classes are not serializable by default in .Net?

Tags:

Developers have to 'opt in' for making classes serializable by explicitly using SerializableAttribute. What could go wrong if classes were serializable by default?

like image 833
Unmesh Kondolikar Avatar asked Dec 10 '10 12:12

Unmesh Kondolikar


People also ask

Why do we need serialization in C#?

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.

Is string serializable C#?

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.

What type of members are not serialized in C#?

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.


2 Answers

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.

like image 62
Cody Gray Avatar answered Oct 12 '22 19:10

Cody Gray


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".

like image 26
Christian Seifert Avatar answered Oct 12 '22 20:10

Christian Seifert