2

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?

nawfal
  • 66,413
  • 54
  • 311
  • 354
Kevin Meredith
  • 39,688
  • 61
  • 199
  • 355
  • possible duplicate of [Why doesn't the XmlSerializer need the type to be marked \[Serializable\]?](http://stackoverflow.com/questions/392431/why-doesnt-the-xmlserializer-need-the-type-to-be-marked-serializable) – nawfal Jul 10 '14 at 09:46

2 Answers2

6

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

Community
  • 1
  • 1
Jesse C. Slicer
  • 19,457
  • 3
  • 66
  • 82
4

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/

Seb
  • 2,617
  • 1
  • 16
  • 14