3

I want to define a flag enum like the following:

[Flags]
[Serializable]
public enum Numbers
{
    [XmlEnum(Name = "One")]
    One = 0x1,
    [XmlEnum(Name = "Two")]
    Two = 0x2,
    [XmlEnum(Name = "Three")]
    Three = 0x4,
    [XmlEnum(Name = "OddNumbers")]
    OddNumbers = One | Three,
    [XmlEnum(Name = "EvenNumbers")]
    EvenNumbers = Two,
    [XmlEnum(Name = "AllNumbers")]
    AllNumbers = One | Two | Three
}

Suppose I create an object which has a Numbers property and I set that property to EvenNumbers. Today, only Two is included in property, but I want to specify EvenNumbers so that if I add Four in the future it will be included in the property as well.

However, if I serialize this object using XmlSerializer.Serialize, the XML will say Two because today this is the same underlying value.

How can I force the serializer to serialize this property as EvenNumbers?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Brian
  • 1,201
  • 2
  • 14
  • 26

1 Answers1

3

Do something like that: Mark the Number property as XmlIgnore and create another property type of string for return the string value of enum.

[Serializable]
public class NumberManager
{
    [XmlIgnore]
    public Numbers Numbers { get; set; }

    [XmlAttribute(AttributeName="Numbers")]
    public string NumbersString
    {
        get { return Numbers.ToString(); }
        set { Numbers = (Numbers) Enum.Parse(typeof (Numbers), value); }
    }
}

Then serialize the NumberManager.

I hope it helps.

denys-vega
  • 3,522
  • 1
  • 19
  • 24
  • This was a good idea to try, but Numbers.ToString() still doesn't know which of the two enumerations was originally used to set the value. Because the underlying integer is the same for both values, I think this may be impossible. However, I wanted to check with the community before giving up. – Brian Mar 16 '15 at 18:14