views:

181

answers:

2

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.

+5  A: 

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.

Greg Beech
+1  A: 

The fundamental difference between the BinaryFormatter and xml serializers (other than the obvious output format) is that binary serialization preserves type information (private/public properties, methods, events, etc...). That's one of the reason this type of serialization is used with remoting. The only requirement is to decorate the type with the SerializableAttribute.

Darin Dimitrov