views:

322

answers:

1

I wish to make a POCO [Serializable] but not any other class members in its class hierarchy tree. I know there is [NonSerialized] which works only for fields, but is there any way to exclude them or choose specific members using [Serializable] on the POCO?

+4  A: 

You should look at the DataContractSerializer; it uses an "opt-in" approach to serialization.

Also it would be a good idea to read XmlSerializer vs DataContractSerializer: Serialization in Wcf to for examples and a comparison between DataContractSerializer and XmlSerializer.

The XmlSerializer has been in .Net since version 1.0 and has served us well for everything from Remoting, Web Services, serializing to a file, etc. However in .Net 3.0 the DataContractSerializer came along. And all of a sudden a lot of guidance suggests that we should use it over the old tried and true XmlSerializer. Wcf even uses this as the default mechanism for serialization. The question is, “Is it really better?”. The verdict is yes, and no. Like most things it depends on your implementation and what you need. For Wcf, you should prefer to use the DataContractSerializer. If you need full control over how the xml looks though, you should go back to the XmlSerializer.

Andrew Hare
Good answer (I've deleted mine) - just to add (for the OP): if you want tight binary serialization, you might consider protobuf-net.
Marc Gravell
@Marc - protobuf-net is a good choice as well and well worth its own answer. If you undelete your answer I will upvote it.
Andrew Hare