yogi
yogi

Reputation: 19601

Readonly DataContract

What difference does it make if I make a property of my DataContract readonly? like below.

[DataContract]
public class data
{
  [DataMember]
  public string datestring 
  { 
     get { return DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss"); } 
  }
  //
  // Other proprties
  //
}

My Jquery request to WCF service was getting Aborted everytime, and when I removed this readonly property it worked. So why can't I make a property like this in my DataContract of WCF service?

Upvotes: 0

Views: 118

Answers (1)

Tim
Tim

Reputation: 28530

While there is no explanation for the reason, the documentation for DataMemberAttribute Class states:

"Properties to which the DataMemberAttribute attribute has been applied must have both get and set fields; they cannot be get-only or set-only."

Edit

I was curious as to why this was the case, so did a little searching. I ran across this in a forum:

"it needs to be get/set so that the values can be assigned when it is being transported across application boundaries." (taken from here).

The author of that forum post also indicates you could use a private setter on the property to workaround this issue:

[DataMember]
public string datestring
{
    get
    {
        return DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss"); 
    }
    private set
    {
    }
}

Note the above code is untested, but should work.

Upvotes: 1

Related Questions