Patrick
Patrick

Reputation: 2790

c#: make a 3rd party object serializable

On my own object I can add the metatag [Serializable] to make it serializable. Now I use a 3rd party library that I need to be serializable. I inspected the code and it should not be a problem. Is there a way to fix this without altering the 3rd party code?

Upvotes: 3

Views: 3218

Answers (4)

Marc Gravell
Marc Gravell

Reputation: 1063198

My advice would be: serialize data, not implementation. The fact of the existence of a 3rd-party object is nothing to do with the data; that is an implementation detail. As such, I always offer the same advice: if serialization ever gets complex, the first thing to do is to introduce a separate DTO model that represents the data in isolation of the implementation, and just map the current state to that DTO. This allows you to handle implementation changes without impact on the storage, and allows otherwise non-serializable objects to be serialized.

Some serializers offer workarounds - for example with protobuf-net you can a: supply the serialization information for any type at runtime, and b: supply a "surrogate" to use automatically when it gets tricky, but - using a DTO model is simpler and easier to maintain.

Your use of [Serializable] suggests BinaryFormatter; in my opinion, this is almost never a good choice for any kind of storage, since BinaryFormatter relies on implementation details. It works nicely for passing data between two in-sync app-domains, though

Upvotes: 6

plinth
plinth

Reputation: 49189

Write an adapter or be prepared to do something more extreme like disassembling the assembly, injecting the serializable attribute and reassembling.

Upvotes: 0

Oybek
Oybek

Reputation: 7243

Exactly take your subclass and make it serializable.

[Serializable] public class Foo: Bar {}

Upvotes: 0

Jamie Dixon
Jamie Dixon

Reputation: 53991

If the types are public you should be able to use the XmlSerializer to do what you want.

There's more information on this here

Serializes and deserializes objects into and from XML documents. The XmlSerializer enables you to control how objects are encoded into XML.

Upvotes: 0

Related Questions