How to tell XmlSerializer to serialize properties with [DefautValue(...)] always?
c#, default-value, winforms, xml-serialization
Solution
As long as you don't need attributes in your Xml, if you use the DataContractSerializer instead you will get the behavior you desire.
[DataContract]
public class Test
{
[DataMember]
[DefaultValue(false)]
public bool AllowNegative { get; set; }
}
void Main()
{
var sb2 = new StringBuilder();
var dcs = new DataContractSerializer(typeof(Test));
using(var writer = XmlWriter.Create(sb2))
{
dcs.WriteObject(writer, new Test());
}
Console.WriteLine(sb2.ToString());
}
produces (minus namespaces etc)
<Test>
<AllowNegative>false</AllowNegative>
</Test>
Problem
I am using `DefaultValue` attribute for the proper `PropertyGrid` behavior (it shows values different from default in bold). Now if I want to serialize shown object with the use of `XmlSerializer` there will be no entries in xml-file for properties with default values. What is the easiest way to tell XmlSerializer to serialize these still? I need that to support "versions", so when I change default value later in the code - serialized property gets value it had serialized with, not "latest" one. I can think about following: - Override behavior of `PropertyGrid` (use custom attribute, so it will be ignoreed by `XmlSerializer`); - Do sort of a custom xml-serialization, where ignore `DefaultValue`'s; - Do something with object before passing it to `XmlSeriazer` so it won't contain `DefaultValue`'s anymore. But there is a chance I miss some secret property what allows to do it without much pain =D. Here is an example of what I want: ``` private bool _allowNegative = false; /// <summary> /// Get or set if negative results are allowed /// </summary> [Category(CategoryAnalyse)] [Admin] [TypeConverter(typeof(ConverterBoolOnOff))] //[DefaultValue(false)] *1 public bool AllowNegative { get { return _allowNegative; } set { _allowNegative = value; ConfigBase.OnConfigChanged(); } } //public void ResetAllowNegative() { _allowNegative = false; } *2 //public bool ShouldSerializeAllowNegative() { return _allowNegative; } *3 //public bool ShouldSerializeAllowNegative() { return true; } *4 ``` If I uncomment (*1), then I have desired effect in `PropertyGrid` - properties with default values are displayed in normal text, otherwise text is bold. However `XmlSerializer` will NOT put properties with default value into xml-file and this is BAD (and I am trying to fix it). If I uncomment (*2) and (*3), then it's totally same as uncommenting (*1). If I uncomment (*2) and (*4), then `XmlSerializer` will always put properties into xml-file, but this happens because they do not have default value anymore and `PropertyGrid` shows all values in bold text.