DataContractAttribute Class

Definition

Specifies that the type defines or implements a data contract and is serializable by a serializer, such as the DataContractSerializer. To make their type serializable, type authors must define a data contract for their type.

public ref class DataContractAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Enum | System.AttributeTargets.Struct, AllowMultiple=false, Inherited=false)]
public sealed class DataContractAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Enum | System.AttributeTargets.Struct, AllowMultiple=false, Inherited=false)>]
type DataContractAttribute = class
    inherit Attribute
Public NotInheritable Class DataContractAttribute
Inherits Attribute
Inheritance
DataContractAttribute
Attributes

Examples

The following example serializes and deserializes a class named Person to which the DataContractAttribute has been applied. Note that the Namespace and Name properties have been set to values that override the default settings.

namespace DataContractAttributeExample
{
    // Set the Name and Namespace properties to new values.
    [DataContract(Name = "Customer", Namespace = "http://www.contoso.com")]
    class Person : IExtensibleDataObject
    {
        // To implement the IExtensibleDataObject interface, you must also
        // implement the ExtensionData property.
        private ExtensionDataObject extensionDataObjectValue;
        public ExtensionDataObject ExtensionData
        {
            get
            {
                return extensionDataObjectValue;
            }
            set
            {
                extensionDataObjectValue = value;
            }
        }

        [DataMember(Name = "CustName")]
        internal string Name;

        [DataMember(Name = "CustID")]
        internal int ID;

        public Person(string newName, int newID)
        {
            Name = newName;
            ID = newID;
        }
    }

    class Test
    {
        public static void Main()
        {
            try
            {
                WriteObject("DataContractExample.xml");
                ReadObject("DataContractExample.xml");
                Console.WriteLine("Press Enter to end");
                Console.ReadLine();
            }
            catch (SerializationException se)
            {
                Console.WriteLine
                ("The serialization operation failed. Reason: {0}",
                  se.Message);
                Console.WriteLine(se.Data);
                Console.ReadLine();
            }
        }

        public static void WriteObject(string path)
        {
            // Create a new instance of the Person class and
            // serialize it to an XML file.
            Person p1 = new Person("Mary", 1);
            // Create a new instance of a StreamWriter
            // to read and write the data.
            FileStream fs = new FileStream(path,
            FileMode.Create);
            XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(fs);
            DataContractSerializer ser =
                new DataContractSerializer(typeof(Person));
            ser.WriteObject(writer, p1);
            Console.WriteLine("Finished writing object.");
            writer.Close();
            fs.Close();
        }
        public static void ReadObject(string path)
        {
            // Deserialize an instance of the Person class
            // from an XML file. First create an instance of the
            // XmlDictionaryReader.
            FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
            XmlDictionaryReader reader =
                XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());

            // Create the DataContractSerializer instance.
            DataContractSerializer ser =
                new DataContractSerializer(typeof(Person));

            // Deserialize the data and read it from the instance.
            Person newPerson = (Person)ser.ReadObject(reader);
            Console.WriteLine("Reading this object:");
            Console.WriteLine(String.Format("{0}, ID: {1}",
            newPerson.Name, newPerson.ID));
            fs.Close();
        }
    }
}
Namespace DataContractAttributeExample
    ' Set the Name and Namespace properties to new values.
    <DataContract(Name := "Customer", [Namespace] := "http://www.contoso.com")>  _
    Class Person
        Implements IExtensibleDataObject
        ' To implement the IExtensibleDataObject interface, you must also
        ' implement the ExtensionData property.
        Private extensionDataObjectValue As ExtensionDataObject 
        
        Public Property ExtensionData() As ExtensionDataObject _
          Implements IExtensibleDataObject.ExtensionData
            Get
                Return extensionDataObjectValue
            End Get
            Set
                extensionDataObjectValue = value
            End Set
        End Property
        
        <DataMember(Name := "CustName")>  _
        Friend Name As String
        
        <DataMember(Name := "CustID")>  _
        Friend ID As Integer
        
        
        Public Sub New(ByVal newName As String, ByVal newID As Integer) 
            Name = newName
            ID = newID
        
        End Sub 
    End Class 
    
    
    Class Test
        
        Public Shared Sub Main() 
            Try
                WriteObject("DataContractExample.xml")
                ReadObject("DataContractExample.xml")
                Console.WriteLine("Press Enter to end")
                Console.ReadLine()
            Catch se As SerializationException
                Console.WriteLine("The serialization operation failed. Reason: {0}", _
                   se.Message)
                Console.WriteLine(se.Data)
                Console.ReadLine()
            End Try
        
        End Sub 
        
        
        Public Shared Sub WriteObject(ByVal path As String) 
            ' Create a new instance of the Person class and 
            ' serialize it to an XML file.
            Dim p1 As New Person("Mary", 1)
            ' Create a new instance of a StreamWriter
            ' to read and write the data.
            Dim fs As New FileStream(path, FileMode.Create)
            Dim writer As XmlDictionaryWriter = XmlDictionaryWriter.CreateTextWriter(fs)
            Dim ser As New DataContractSerializer(GetType(Person))
            ser.WriteObject(writer, p1)
            Console.WriteLine("Finished writing object.")
            writer.Close()
            fs.Close()
        
        End Sub 
        
        Public Shared Sub ReadObject(ByVal path As String) 
            ' Deserialize an instance of the Person class 
            ' from an XML file. First create an instance of the 
            ' XmlDictionaryReader.
            Dim fs As New FileStream(path, FileMode.OpenOrCreate)
            Dim reader As XmlDictionaryReader = XmlDictionaryReader. _
              CreateTextReader(fs, New XmlDictionaryReaderQuotas())
            
            ' Create the DataContractSerializer instance.
            Dim ser As New DataContractSerializer(GetType(Person))
            
            ' Deserialize the data and read it from the instance.
            Dim newPerson As Person = CType(ser.ReadObject(reader), Person)
            Console.WriteLine("Reading this object:")
            Console.WriteLine(String.Format("{0}, ID: {1}", newPerson.Name, newPerson.ID))
            fs.Close()
        
        End Sub 
    End Class 
End Namespace

Remarks

For more information about this API, see Supplemental API remarks for DataContractAttribute.

Constructors

DataContractAttribute()

Initializes a new instance of the DataContractAttribute class.

Properties

IsNameSetExplicitly

Gets whether Name has been explicitly set.

IsNamespaceSetExplicitly

Gets whether Namespace has been explicitly set.

IsReference

Gets or sets a value that indicates whether to preserve object reference data.

IsReferenceSetExplicitly

Gets whether IsReference has been explicitly set.

Name

Gets or sets the name of the data contract for the type.

Namespace

Gets or sets the namespace for the data contract for the type.

TypeId

When implemented in a derived class, gets a unique identifier for this Attribute.

(Inherited from Attribute)

Methods

Equals(Object)

Returns a value that indicates whether this instance is equal to a specified object.

(Inherited from Attribute)
GetHashCode()

Returns the hash code for this instance.

(Inherited from Attribute)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
IsDefaultAttribute()

When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.

(Inherited from Attribute)
Match(Object)

When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(Inherited from Attribute)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
ToString()

Returns a string that represents the current object.

(Inherited from Object)

Explicit Interface Implementations

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Maps a set of names to a corresponding set of dispatch identifiers.

(Inherited from Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Retrieves the type information for an object, which can be used to get the type information for an interface.

(Inherited from Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(Inherited from Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Provides access to properties and methods exposed by an object.

(Inherited from Attribute)

Applies to

See also