Search code examples
c#serializationdatacontractdeserialization

How to find out if class has DataContract attribute?


I'm writing a serialization function that needs to determine whether class has DataContract attribute. Basically function will use DataContractSerializer if class has DataContract attribute, otherwise it will use XmlSerializer.

Thanks for your help!


Solution

  • The simplest way to test for DataContractAttribute is probably:

    bool f = Attribute.IsDefined(typeof(T), typeof(DataContractAttribute));
    

    That said, now that DC supports POCO serialization, it is not complete. A more complete test for DC serializability would be:

    bool f = true;
    try {
        new DataContractSerializer(typeof(T));
    }
    catch (DataContractException) {
        f = false;
    }