Search code examples
c#.netdatacontractserializerdatacontractxml-deserialization

Is good practice to throw exceptions in a property with DataMember attribute applied?


DataContract and DataMember attributes may be also used in order to serialize an object to file and for deserialization, by using a DataContractSerializer. Suppose we have a class with the following private field and public property.

public class MyClass
{
    private int positiveValue;

    public int PositiveValue
    {
        get { return positiveValue; }
        set
        {
            if (value < 1)
                throw new ArgumentOutOfBoundException(...);
            positiveValue = value;
        }
    }
}

Now suppose we have an XML file containing the state of a previously serialized object, and assume that the user has modified this file, specifying an incorrect value (that is a non positive value) for the PositiveValue property. During deserialization an exception would be thrown, since the value in the file is invalid.

Suppose we want to deserialize a list of MyClass objects from a file: if some object is not valid, an exception is thrown. Is it possible to make sure that the DataContractSerializer ignores invalid objects? Moreover, taking into account the problem just explained, is good practice to throw exceptions in a property with DataMember attribute applied?


Solution

  • In terms of a list, no you can't make DCS ignore invalid objects. If an exception occurs, the entire deserialize is aborted. If it doesn't throw, it it going to be added to your list.

    I would consider checking validity after-and-separate-from deserialization. In some cases, you might be able to just say "ignore invalid items in lists", but frankly in most cases if there is any problem you just want to reject the entire thing.