C# – Do We Really Need SerializableAttribute?

cserialization

I understand we need it to mark a class whose objects can be serialized, but do we strictly need this for behind the hood logic to work? We could just serialize the object using necessary methods. On the other hand, if we want to prevent serialization, then having this attribute makes sense, in that case [NonSerialized()] becomes redundant.

Considering syntax and semantics, what is the necessity of this attribute?

Best Answer

do we strictly need this for behind the hood logic to work?

No. Most serialization libraries (I.E. Newtonsoft.JSON, System.Xml.Serialization) do not require the [Serializable] attribute and instead assume that public fields and properties should be serialized and private ones should not with some methods for opting out.

As for BinaryFormatter it defaults to serialize everything, including private fields. This is a bit more potentially dangerous, as it could expose sensitive or unintentional data if the class was not meant to be serialized.

See https://stackoverflow.com/questions/2982376/why-is-serializable-attribute-required-for-an-object-to-be-serialized

Related Topic