WCF: DataMember attribute on property vs. member

Viewed 42011

In wcf, what is the difference between applying the DataMember attribute on a property

private int m_SomeValue;

[DataMember]  
public int SomeValue {
  get {...}
  set {...}
}

instead of a member variable

[DataMember]  
private int m_SomeValue;

public int SomeValue {
  get {...}
  set {...}
}

?

7 Answers

In general, you should favor applying the DataMember attribute on the property, rather than on the private field. The only reason to apply the attribute to the field instead is if the property were read-only (i.e. it has no setter).

As long as you use the Name marker, the contract is identical regardless of whether the field or property is used.

[DataMember(Name="SomeValue")]
private int m_SomeValue;

However, there may be some permissions issues accessing private members, in particular on silverlight and CF - in which case I would recommend using the public property as the data-member. Actually, I would tend to always use a property unless I had a very good reason...

In theory, and as long as you keep m_SomeValue always equal to SomeValue (like a simple getter/setter), nothing. Other than the name of the variable exposed by the WCF. (Obviously, if you tag the m_ variable, then your proxy class will also have the same m_ name. The proxy class will generate a public property whether you use a public/protected/internal/private field or property.

However, if you have any special logic in your accessors that may modify the value returned (ToUpper()ing a string, for example), then you would return a different value.

Related