Malice
Malice

Reputation: 3977

Are Types Serializable by Default?

I am reading the book Learning WCF by Michele Leroux Bustamante. One of the labs is dealing with DataContracts and I am not seeing the expected behaviour of the application as described in the book. Basically an exception should be thrown because a type is not defined as a DataContract and is unable to be serialised.

The type, LinkItem, is defined as follows, without DataContract or DataMember attributes:

public class LinkItem
{
    public DateTime Start { get; set; }
    public DateTime End { get; set; }
    // Other properties omitted for simplicity
}

The code to host the service is as follows:

using (ServiceHost host = new ServiceHost(typeof(GigManager.GigManagerService)))
{
    host.Open();
    // Code omitted for simplicity
}

When I run the application there is no exception thrown. According to the book, when I visit the XSD schema for the service at http://localhost:8000/?xsd=xsd2, I should see <xs:schema elementFormDefault="qualified" targetNamespace="http://schemas.datacontract.org/2004/07/ContentTypes"> only when the DataContract attribute is applied. I see the same targetNamespace definition whether the DataContract attribute is applied to the class or not.

My guess is that something has changed in the .NET Framework between the version targeted by the book (2.0) and the version I am running (4.5). As I have only just started to get to grips with WCF I am unable to say for sure. Can anyone more knowledgeable clarify if this is the case or otherwise explain why the exception is not being thrown?

Upvotes: 1

Views: 174

Answers (1)

Fede
Fede

Reputation: 44068

From MSDN:

The DataContractSerializer is designed to serialize data contract types. However, it supports many other types, which can be thought of as having an implicit data contract. The following is a complete list of types that can be serialized:

  • All publicly visible types that have a constructor that does not have parameters. [...]

  • Data contract types. [...]

  • Collection types. [...]

  • Enumeration types. [...]

  • .NET Framework primitive types. [...]

  • Other primitive types. [...]

  • Types marked with the SerializableAttribute attribute.[...]

See the MSDN article for more information.

Upvotes: 3

Related Questions