Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell C# to omit creation of attributes that are default during serialization?

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?

like image 687
MrFox Avatar asked Apr 24 '09 10:04

MrFox


2 Answers

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

like image 77
Rowland Shaw Avatar answered Oct 14 '22 01:10

Rowland Shaw


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.

like image 27
Marc Gravell Avatar answered Oct 14 '22 02:10

Marc Gravell