Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Binary Serialization require the object to be marked as serializable?

I was using the xml serializer but when I switched to binary serialization, it throws an exception:

Runtime error: dotNet runtime exception: Type 'MyTypes.MyObject' in Assembly 'MyTypes, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

Why is it different than an xml serializer in the way it asks this?

Just marking the object as serializable is enough to solve this? I don't want to specify how the serialization should occur.

like image 946
Joan Venge Avatar asked May 23 '26 15:05

Joan Venge


1 Answers

XmlSerializer is safe to use in all cases because it only serializes publicly accessible data, that users of the class could access anyway.

Any of the runtime formatters (including BinaryFormatter) serialize both publicly and privately accessible information, so may give callers access to information that they otherwise shouldn't have. By marking your type as [Serializable] you're effectively saying that you've thought about this and are granting permission to anybody to look at the serialized information about your type.

This is a "safe by default" choice so that you don't accidentally end up serializing sensitive data like credit card details or whatever into places they shouldn't be such as logs or databases.

like image 72
Greg Beech Avatar answered May 26 '26 05:05

Greg Beech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!