I love automatic xml serialization of public members in C#. It saves you so much time. But now I may have reached the limits, or do you know how to do that?
What I want to achieve is that nothing is written for a member when it has a default value. That is is easy with a standard type like "int" for example:
[XmlElement(ElementName = "Test", IsNullable = false), DefaultValue(0)]
public int Test = 0;
So as long as "Test" equals 0 nothing is written on serialization.
But what about structs as members? For example:
public struct Vector2 {
public float x;
public float y;
public Vector2(float x = 0.0f, float y = 0.0f) {
this.x = x;
this.y = y;
}
...
}
public class ToSerialize {
[XmlElement(ElementName = "Shift", IsNullable = false), DefaultValue(new Vector2(0,0))]
public Vector2 Shift = new Vector2(0, 0);
...
}
This does not work because "new Vector2(0,0)" is not a const. Maybe I am just unable to figure out that attribute syntax. How can I make it work? This question is about coding comfort, so I am not interested in solutions like "write your own serialization code" or other proposals which result in lengthy code. If you know that this does not work with the automatic serialization system that would be an answer too.