How to specify a NonSerialized field with public accessors for XML Serialization
Asked Answered
V

1

6

How do you specify a NonSerialized field with public accessors for XML Serialization?

[NonSerialized]
public String _fooBar;
//Declaring the property here will serialize the _fooBar field
public String FooBar
{
    get { return _fooBar; }
    set { _fooBar = value; }
}
Verve answered 6/4, 2011 at 1:28 Comment(8)
I assume this is a made up example? Otherwise you can just use an auto property and mark that as NonSerialized.Pessimist
The attribute cannot be applied to properties.Coattail
@Pessimist I actually get "Attribute 'NonSerialized' is not valid on this declaration type. It is only valid on 'field' declarations." on an auto-property...Verve
Yes, Hans is right - my mistake.Pessimist
@Pessimist - [XmlIgnore] works with auto-properties, though.Verve
@MPelletier: Would have been good to know you are looking for XML serialization from the beginning - kudos to @Hans for catching it.Pessimist
@Pessimist - I just, very naively, discovered that it made a difference. My bad.Verve
Glad you got it resolved - and we both learnt something in the process ;-)Pessimist
C
17

Properties don't get serialized by BinaryFormatter, only fields. The [NonSerialized] attribute has no meaning for XML serialization. Use [XmlIgnore] instead.

Coattail answered 6/4, 2011 at 1:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.