Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataMember attribute set to field or property?

Tags:

c#

attributes

In which way should I use DataMemeber attribute ?

I.

 [DataMember]
 internal protected string _FirstName="";

[DataMember]
public string FirstName { get { return _FirstName; } 
internal protected set { _FirstName=(value!=null?value:""); } }

II.

internal protected string _FirstName="";

    [DataMember]
    public string FirstName { get { return _FirstName; } 
    internal protected set { _FirstName=(value!=null?value:""); } }

III.

[DataMember]
internal protected string _FirstName="";


    public string FirstName { get { return _FirstName; } 
    internal protected set { _FirstName=(value!=null?value:""); } }
like image 458
netmajor Avatar asked Aug 25 '11 14:08

netmajor


People also ask

What does DataMember attribute do?

Remarks. Apply the DataMemberAttribute attribute in conjunction with the DataContractAttribute to identify members of a type that are part of a data contract. One of the serializers that can serialize data contracts is the DataContractSerializer. The data contract model is an "opt-in" model.

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.

What is DataMember in asp net?

The DataMember property sets or returns a string value that contains the name of the data member that will be retrieved from the object referenced by the DataSource property. The name is not case sensitive. This property is used to create data-bound controls with the Data Environment in Visual Basic 6.

What is DataContract attribute?

[DataContract] attribute specifies the data, which is to serialize (in short conversion of structured data into some format like Binary, XML etc.) and deserialize(opposite of serialization) in order to exchange between the client and the Service.


2 Answers

1st is definitely not correct, as serialization will happen twice. Between 2nd and 3rd I personally prefer 2nd, as encapsulating implementation.

like image 163
adontz Avatar answered Sep 21 '22 00:09

adontz


The second one. This exposes only the property as a data member. That's what you want. You don't want to have the field exposed.

like image 34
Daniel Hilgarth Avatar answered Sep 20 '22 00:09

Daniel Hilgarth