views:

342

answers:

3

I have a class that is serialized to a XML file. There are several properties that are rarely used but always created. If I delete them within the XML the deserialization still works, because they have the default value.

These unnecessary (bool) attributes make the XML harder to read.

Can I somehow tell C# to omit elements or attributes that still have default value?

+8  A: 

Specify the DefaultValueAttribute, and if the value matches, it won't be output.

Rowland Shaw
´[System.ComponentModel.DefaultValue(false)]´ did it for bool values - Thank you :)
MrFox
A: 

Use the XMLIgnore() Attribute to mark a property to be ingnored in Serialization / Deserialization.

Ben
No, that will **alays** exclude it; the question is to exclude it when it has the default value.
Marc Gravell
I think OP wants to just ignore properties that have a default value. Your solution would cause properties to always be ignored.
Tormod Fjeldskår
+4  A: 

Rowland has the answer for simple values. For more complex scenarios, you can add a method called public bool ShouldSerializeFoo() (for property Foo) - it it returns false, it won't get serialized.

Marc Gravell
I would just like to mention the EditorBrowsableAttribute which can be used to prevent auxiliary members like these from appearing in IntelliSense.
Tormod Fjeldskår
Instead of ShouldSerializeFoo(), a bool FooSpecified Property can also be used.
David Schmitt
If you go with the *Specified patter, you need to remember to mark it [XmlIgnore], IIRC
Marc Gravell