Kevin Meredith
Kevin Meredith

Reputation: 41909

Why doesn't the class need to be marked with either the [DataContract] or [Serializable] attributes to be serialized?

Microsoft provides code in its article, "How to serialize an object to XML by using Visual C#."

using System;

public class clsPerson
{
  public  string FirstName;
  public  string MI;
  public  string LastName;
}

class class1
{ 
   static void Main(string[] args)
   {
      clsPerson p=new clsPerson();
      p.FirstName = "Jeff";
      p.MI = "A";
      p.LastName = "Price";
      XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
      x.Serialize(Console.Out, p);
      Console.WriteLine();
      Console.ReadLine();
   }
}    

However, why doesn't the class, clsPerson, need to be marked with either the [DataContract] or [Serializable] attributes?

Upvotes: 2

Views: 3900

Answers (2)

Seb
Seb

Reputation: 2715

By design, XML serialization serializes public fields and public properties with get AND set accessor. The serialized type must also have a parameterless constructor. It's the only contract \o/

Upvotes: 4

Jesse C. Slicer
Jesse C. Slicer

Reputation: 20157

Because the XmlSerializer doesn't require those attributes to be placed on the class. Only BinaryFormatter and DataContractSerializer do. And for that matter, DataContractSerializer can do without.

See related question: Why is Serializable Attribute required for an object to be serialized

Upvotes: 6

Related Questions