0

Why are fields not serializable via the XML serializer, in C#, whereas properties are? I know that properties are actually methods, but I don't see why that should make a difference. Does anyone know the answer to this?

Thanks so much!

Zachary Kniebel
  • 4,686
  • 3
  • 29
  • 53
  • 7
    Why do you think that fields are not serializable? – Daniel Hilgarth Jul 11 '13 at 13:10
  • More than likely either the field is of a data-type that is not yet serializable, or the field is not public. – Matthew Jul 11 '13 at 13:14
  • 1
    Do you have a _specific_ serializer in mind? Like `XmlSerializer` or `DataContractJsonSerializer` or `protobuf-net` or something else? The answer would depend on those as it's up to their implementations and designs they wish to include fields, properties, indexers or whatever their intended _usage_ is. – Chris Sinclair Jul 11 '13 at 13:15
  • One of the answers on http://stackoverflow.com/questions/653536/difference-between-property-and-field-in-c-sharp-3-0 stated it (sorry I am on my phone and dont have the "share" link) but I can't find any information on it – Zachary Kniebel Jul 11 '13 at 13:15
  • 1
    @ZacharyKniebel: There is only one answer that claims this: http://stackoverflow.com/a/653543/572644. And it has a comment that states that it is incorrect. – Daniel Hilgarth Jul 11 '13 at 13:18

2 Answers2

7

Fields are serializable :

XML serialization serializes the public fields and properties of an object, or the parameters and return values of methods, into an XML stream that conforms to a specific XML Schema definition language (XSD) document. XML serialization results in strongly typed classes with public properties and fields that are converted to XML. System.Xml.Serialization contains the classes necessary for serializing and deserializing XML.

From MSDN

2GDev
  • 2,478
  • 1
  • 20
  • 32
  • Thanks for your help. I didn't realize, initially, that what is and is not serializable could be dependent on the type of serialization – Zachary Kniebel Jul 11 '13 at 13:26
2

Fields are serializable. In fact, all fields are by default serialized unless you mark them with the NonSerialized attribute.

If you talk about XML serialization, then only public fields will be serialized because XML serialization only serializes the public interface of an object.

cremor
  • 6,669
  • 1
  • 29
  • 72