M. Jahedbozorgan
M. Jahedbozorgan

Reputation: 7054

Why classes not marked with Serializable cannot be serialized using BinaryFormatter?

As we all know and mentioned in MSDN site:

The serialization architecture provided with the .NET Framework correctly handles object graphs and circular references automatically. The only requirement placed on object graphs is that all objects referenced by the object that is being serialized must also be marked as Serializable. If this is not done, an exception will be thrown when the serializer attempts to serialize the unmarked object.

My question is why this constraint is applied? (If this is a constraint! ;-))

Upvotes: 5

Views: 3004

Answers (2)

Hans Passant
Hans Passant

Reputation: 942448

BinaryFormatter has very unusual powers, nothing else resembles what it does. It can create an object of your class without running its constructor. And it can give a value to your properties without running the property setter accessor methods.

Otherwise nothing particular magical about this, it simply persists the values of the fields of your class object. And restores them when the object is deserialized.

Not every class is suitable to be treated like this, either because of security concerns or because field values depend on runtime state too much. Note how security is an issue since an attacker could manipulate the serialized data and get your object into an inconsistent state, state that is exploitable. Say an IsAdministrator property. A good example of critical runtime state is the Control.Handle property, it can never have the same value when you deserialize.

These are practical constraints that the BinaryFormatter class can not figure out by itself. It needs help, an explicit okay that it is safe to do this. This cannot be a formal okay when you write the code to de/serialize the object, that would be easy but it in practice you don't know enough about the class since you did not write it. The class author needs to do this, they do so by giving it the [Serializable] attribute.

Upvotes: 9

jjee
jjee

Reputation: 265

I believe the answer at https://stackoverflow.com/a/12461510/5830656 answers your question of why is this constraint applied -

"to prevent data accidentally leaking across a remoting boundary"

i.e. the reason it is there it is because it is a design decision of BinaryFormatter, a safe-guard to ensure the programmer really meant the data to be serialized that is being serialized by BinaryFormatter.

That MSDN article also states -

a class cannot be made serializable after it has been compiled.

(meaning attempting to make it serializable at execution-time by adding the attribute type using reflection) so it is a constraint of the implementation of BinaryFormatter that the SerializableAttribute must be specified for compilation of types to be serialized using it.

Upvotes: 3

Related Questions