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
  • 70,104
  • 56
  • 326
  • 368
Kevin Meredith
  • 41,036
  • 63
  • 209
  • 384
  • 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,901
  • 3
  • 68
  • 87
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,637
  • 1
  • 17
  • 15