2

I have just started WCF. I had a question with respect to serialization. I know WCF uses DataContract Serialization by default behind the scenes. I have looked at some code online by Aaron Skonnard in his article http://msdn.microsoft.com/en-us/magazine/cc163569.aspx. The code below is from his article. In this he has written code to serialize a Person object. My question is doesn't WCF do this behind the scenes. Why do we have to write the serialization logic? and then de-serialize it back again. As a WCF starter I am confused as to when to write this code and when not to. I think this would just work fine if there were no serialization logic written. Help appreciated!

static void WriterPersonSerializable()
{

Person p = new Person("Bob", 34, "secret");

p.spouse = new Person("Jane", 33, "secret");

using (FileStream fs = new FileStream("person.xml", FileMode.Create))
using (XmlDictionaryWriter writer =
    XmlDictionaryWriter.CreateTextWriter(fs))
{
    DataContractSerializer serializer =
        new DataContractSerializer(typeof(Person));
    serializer.WriteObject(writer, p);
}
1
  • 2
    You don't have to write any such code. You just use the DataContract and DataMember attributes to tell WCF how you want Person object to be serialized. WCF uses the DataContractSerializer under the covers to do the serialization for you. That article is showing you the inner-workings of WCF, so he provides code that WCF uses to do the serialization (loosely-speaking). Commented Feb 22, 2013 at 23:19

1 Answer 1

2

You don't have to do something like that. Ofcourse, you can setup your own serialization. But by default it is ok if you just mark your classes by [DataContract] attribute and properties of classes by [DataMember] attribute. After that all you need to do is to inform your service about what classes it should be able to serialize/deserialize in [ServiceKnownType] attribute. That's it, everything will work out of the box.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.