Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is using [DataMember(EmitDefaultValue = false)] not recommended?

In WCF you can define a contract using the [DataContract] and [DataMember] attributes, like this:

[DataContract] public class Sample  {     [DataMember(EmitDefaultValue = false, IsRequired = false)]     public string Test { get; set; } } 

This article on the MSDN states that using EmitDefaultValue = false is not recommended:

snippet

However, i like to use this, because the XML that is generated using this construction is cleaner. Not specifying this setting results in:

<Sample>     <Test xsi:nil="true"/> </Sample> 

while using the setting the element is ommited when there is no value:

<Sample> </Sample> 

I'm curious to what the reasoning behind that statement is. Specifically since both snipptes of XML look equivalent to me (and both last part can be deserialized correctly for this contract).

What is the reasoning behind this statement?

like image 786
oɔɯǝɹ Avatar asked Mar 21 '11 19:03

oɔɯǝɹ


People also ask

Is DataMember attribute required?

Data Member are the fields or properties of your Data Contract class. You must specify [DataMember] attribute on the property or the field of your Data Contract class to identify it as a Data Member.

What is EmitDefaultValue?

It is occasionally desirable to omit a data member from the serialized data when it is set to its default value. To do this, set the EmitDefaultValue property to false (it is true by default). Setting the EmitDefaultValue property to false is not a recommended practice.

What is Datacontract and DataMember?

A datacontract is a formal agreement between a client and service that abstractly describes the data to be exchanged. In WCF, the most common way of serialization is to make the type with the datacontract attribute and each member as datamember.


1 Answers

The reason is at the bottom of the article that you link to. The short version is:

  • When the EmitDefaultValue is set to false, it is represented in the schema as an annotation specific to Windows Communication Foundation (WCF). There is no interoperable way to represent this information. In particular, the "default" attribute in the schema is not used for this purpose, the minOccurs attribute is affected only by the IsRequired setting, and the nillable attribute is affected only by the type of the data member.

  • The actual default value to use is not present in the schema. It is up to the receiving endpoint to appropriately interpret a missing element.

like image 193
Shiraz Bhaiji Avatar answered Oct 02 '22 14:10

Shiraz Bhaiji