netmajor
netmajor

Reputation: 6585

DataMember attribute set to field or property?

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:""); } }

Upvotes: 6

Views: 3220

Answers (2)

adontz
adontz

Reputation: 1438

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

Upvotes: 7

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174397

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.

Upvotes: 4

Related Questions