.Net Web Services: Rules Governing Objects that can be Serialized to XML

Following are the considerations that should be kept in mind while designing data classes that need to be used as parameters or return type of Web Method(s) in .Net Web Service(s), so that the concerned Web Service(s) can be consumed by any client:-

1. Only classes with a public, default constructor will be serialized to XML: This means that .Net will not recognize an object to be serialized to XML at all, if it doesn't have a parameterless default constructor i.e. either the class should have no explicit constructor at all; or, if it does have an explicit constructor then it should also have an explicit parameterless public constructor

  • /*This is not a public default constructor, we also have to
    provide a public parameterless explicit constructor for this
    class to be serialized to XML, if we provide a parameterized
    constructor as below, assuming class name is Employee*/

    public Employee(string Name)
    {
    EmpName = Name;
    }
  • /*This is a public default constructor, that needs to be
    provided in a class, if we provide a parameterized constructor
    as above; for it to be serialized, assuming class name is Employee*/
    public Employee()
    {
    }

2. Only public fields and public properties will be serialized to XML
3. Read-only fields and read-only properties will not be serialized to XML
4. Methods and other type information associated with the class will not be serialized


Ref: .Net Web Services, Keith Ballinger

Comments