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.
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:
getas well as asetmethod)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.