views:

18

answers:

2

Hi All,

Is it necessary to decorate custom objects with [DataContract] and [DataMember] when using shared assemblies (as opposed to auto proxy generation)?

The reason I ask is that I have encountered the following scenario:

Suppose the following object is implemented in my service:

public class baseClass
{
  Guid _guid;

  public baseClass()
  {
      _guid = Guid.NewGuid()
  }

  public Guid ReturnGuid { get {return _guid;}}
}

public class newClass : baseClass
{
    int _someValue;

    public newClass {}

    public int SomeValue
    {
       get {return _someValue;}
       set {_someValue = value;}
    }
}

[ServiceContract]
public IService
{
   [OperationContract]
   newClass SomeOperation();
}

In my client (with shared assemblies) I can happily receive and use a serialized newClass when SomeOperation is called - even though I have not marked it as a DataContract.

However, as soon as I do mark it with DataContract and use DataMember then it complains that set is not implemented on ReturnGuid in the base class.

Could somebody explain why it works fine when I do not decorate with DataContract and DataMember.

Many thanks.

A: 

When .NET 3.0 was first released, in order to serialize an object using the DataContractSerializer all classes and properties had to be marked with those attributes no matter whether you used shared assemblies or generated proxies. Since .NET 3.5 SP1 you no longer need to put those attributes as all public properties will be serialized. The problem in your case is that by default the ReturnGuid is not serialized as it has no setter and if you put the attributes you enforce the serialization of a property which has no setter and it complains.

Despite the fact that you can omit those attributes I would recommend you using them on all of your entities. As for the ReturnGuid property, if you want this transmitted over the wire add a setter.

public Guid ReturnGuid 
{ 
    get { return _guid; } 
    set { _guid = value; }
}
Darin Dimitrov
What are the reasons for using these attributes, even if we don't have to?
Andrew Shepherd
A: 

Microsoft introduced a change in the .NET 3.5 Service Pack 1 in that the DataContract/DataMember attributes aren't required anymore.

So if you don't want to, you don't need to have those attributes. If you omit those attributes, the DataContractSerializer will serialize the object class just like the XmlSerializer would:

  • serializes all public read/write properties (properties which have both a get as well as a set method)
  • serializes them in the order they appear in the class definition

So no - you don't have to have those attributes anymore. But if you leave them out, you also loose the benefits of having them around: you cannot define a member to be required, you cannot define the order in which the attributes should be ordered in the serialized XML etc.

marc_s