views:

73

answers:

2

I've seen many different ways to serialize objects in C# that I'm not sure which one to use and when.

In the current situation I'm serializing for exposure through WCF so I'm guessing the [DataContract] attribute is the way to go.

Currently I'm reading in some XML, then exposing the resulting object through WCF. So I am deserializing XML for which I have no access to the original classes (therefore I'm rebuilding the class and can implement serialization whichever way I want). Then it has to be serializable for the WCF.

But if [DataContract] is good for this case, then why wouldn't I use it all the time instead of ISerializable, or the [Serializable] attribute?

So a bit of two questions in one, which to use for this problem, and why are there different ways to serialize.

+2  A: 

DataContract is a good place to start for basic serializing. But if you want to control exactly how the object is serialized use the ISerializable interface. Also, the data contract attribute does not get inherited, but the ISerializable will

ISerializable has been around since .net 1.1. DataContract was introduced in .net 3.0 to simplify serializing for most cases.

Josh
+2  A: 

Using ISerializable, by implementing GetObjectData, you can customize the way an object is serialized/deserialized within the object's class without having to create a serializer

If you create a WCF service, I think you should stick to DataContract. One of its big advantages is the opt in (i.e. no bad surprises) mechanism.

vc 74