How to: Create a Basic Data Contract for a Class or Structure

This topic shows the basic steps to create a data contract using a class or structure. For more information about data contracts and how they are used, see Using Data Contracts.

For a tutorial that walks through the steps of creating a basic Windows Communication Foundation (WCF) service and client, see the Getting Started Tutorial. For a working sample application that consists of a basic service and client, see Basic Data Contract.

To create a basic data contract for a class or structure

  1. Declare that the type has a data contract by applying the DataContractAttribute attribute to the class. Note that all public types, including those without attributes, are serializable. The DataContractSerializer infers a data contract if the DataContractAttribute attribute is absent. For more information, see Serializable Types.

  2. Define the members (properties, fields, or events) that are serialized by applying the DataMemberAttribute attribute to each member. These members are called data members. By default, all public types are serializable. For more information, see Serializable Types.

    Note

    You can apply the DataMemberAttribute attribute to private fields, causing the data to be exposed to others. Be sure that the member does not contain sensitive data.

Example

The following example shows how to create a data contract for the Person type by applying the DataContractAttribute and DataMemberAttribute attributes to the class and its members.

using System;
using System.Runtime.Serialization;

[DataContract]
public class Person
{
    // This member is serialized.
    [DataMember]
    internal string FullName;

    // This is serialized even though it is private.
    [DataMember]
    private int Age;

    // This is not serialized because the DataMemberAttribute
    // has not been applied.
    private string MailingAddress;

    // This is not serialized, but the property is.
    private string telephoneNumberValue;

    [DataMember]
    public string TelephoneNumber
    {
        get { return telephoneNumberValue; }
        set { telephoneNumberValue = value; }
    }
}
<DataContract()> _
Public Class Person
    ' This member is serialized.
    <DataMember()> _
    Friend FullName As String

    ' This is serialized even though it is private.
    <DataMember()> _
    Private Age As Integer

    ' This is not serialized because the DataMemberAttribute 
    ' has not been applied.
    Private MailingAddress As String

    ' This is not serialized, but the property is.
    Private telephoneNumberValue As String

    <DataMember()> _
    Public Property TelephoneNumber() As String
        Get
            Return telephoneNumberValue
        End Get
        Set
            telephoneNumberValue = value
        End Set
    End Property
End Class

See also