Define Data contracts

If you could recall the previous post about Service contracts, I mentioned that you must use serializable types as return/parameter types in your exposed methods. When you build custom types (and you’ll certainly do so) you’ll need to tell WCF either implicitly or explicitly how to serialize your types.

The implicit way is to mark your custom types as serializable, with the SerializableAttribute class. This isn’t too exciting, and doesn’t require you to use data contracts, which are cooler, and will be covered by the exam test. Anyway, you should know that all publicly visible properties and fields will be serialized when you use the implicit method.

The explicit way is to mark your custom types with the DataContractAttribute and the fields/properties with the DataMemberAttribute. Then you’ll gain a finer control over how WCF will serialize and deserialize those types. The DataContractAttribute has the following named parameters:

Named Parameters of DataContractAttribute
IsReference A Boolean value indicating whether or not the custom type is a reference type.
Name The name of the data contract for the type.
Namespace The namespace of the data contract type.

When you mark a type (which can be a class, struct or enumeration) with the DataContractAttribute, then you must mark fields or properties you want to participate in the serialization process by the DataMemberAttribute. Note that this attribute doesn’t respect the accessibility modifiers of your types, anything marked with it will be serialized, expect static properties/fields.

With the DataMemberAttribute, you can define the following named parameters:

  • EmitDefaultValue: whether or not to serialize the default value for the property/filed.
  • IsRequired: sets a value whether or not the member must be present on deserialization.
  • Name: the name of the data member,
  • Order: the order (ordinal number) in which to serialize/deserialize the object.


Further Readings

Using Data Contracts

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: