6

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?

1
  • 2
    The fact that binary serialization (and hence [Serializable]) mostly disappeared from .NET Core I think tells you a lot about it. (Yes, I know it's somewhat back in .NET Core 2.x). Commented Sep 25, 2018 at 21:40

1 Answer 1

8

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.