Hello,
I have a question about XmlSerialization. I have a class with a private
field called createDate of the type DateTime. In the constructor of my class
I use DateTime. Now to create a timestamp that is assigned to the field
createDate. Because I want to encapsulate as much as possible of my class
data and don't want clients of my class to change the createDate but only
read it, I encapsulate the createDate field with a get Property. Now I want
this class to be the return type of a WebService I created and I want
consumers of my WebService to be able to read the createDate from the Xml
response from the WebService, so I added the XmlElementAttribute attribute to
my CreateDate property. The problem I run into is described on MSDN for the
XmlElementAttribute:
"Apply the XmlElementAttribute to public fields or public read/write
properties to control characteristics of the XML elements such as the element
name and namespace."
So, either the field needs to be public or my property needs to be a
read/write property. I think public fields are a bad practice in general, and
by adding a set method to my CreateDate property, I am opening up my class
more than I want to: clients of my class are now able to set the CreateDate
which I do not want them to be able to.
I hope you understand my problem here. Why should the XmlElementAttribute be
applied to read/write properties only and not to read properties? And what is
the best practice for this situation? I do want the createDate to be in the
Xml result of my WebService, but I don't want clients of my class to be able
to set the createDate.