Search code examples
c#.netdatacontractserializer

Handling values which are not part of the enumeration with datacontract serialization C#


I have a piece of code which uses the datacontract serializer to serialize and deserialize to/from an .xml file. One of the public property is an enumeration. There is a probability that .xml will be edited by hand and then it is a possible that property which is an enumeration may have some value which is not part of the enumeration. In this case the datacontract fails while deserailizing.

How can this be handled ? What is a good solution ?


Solution

  • Try this:

    public enum E
    {
        One, 
        Two
    }
    
    [DataContract]
    public class C
    {
        [DataMember]
        private string myField;
    
        public E MyProperty 
        {
            get 
            { 
                E result;
                return Enum.TryParse<E>(myField, out result) ? result : default(E);
            }
            set { myField = value.ToString(); }
        }
    }
    

    Since the user can put anything into corresponding XML tag, then I can't see best solution, than store property value in the string field.

    If performance is critical, you can store enum value in regular property, and work with string field only when serializing/deserializing data (see OnSerializingAttribute/OnDeserializedAttribute).