Alex
Alex

Reputation: 170

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!

Upvotes: 15

Views: 6279

Answers (4)

Abacus
Abacus

Reputation: 2119

I found that in addition to checking for DataContractAttribute, you should also allow for System.ServiceModel.MessageContractAttribute and System.SerializableAttribute.

bool canDataContractSerialize = (from x in value.GetType().GetCustomAttributes(true)
                                 where x is System.Runtime.Serialization.DataContractAttribute
                                 | x is System.SerializableAttribute
                                 | x is System.ServiceModel.MessageContractAttributex).Any;

Upvotes: 0

EgorBo
EgorBo

Reputation: 6142

    bool hasDataContractAttribute = typeof(YourType)
         .GetCustomAttributes(typeof(DataContractAttribute), true).Any();

Upvotes: 7

alexdej
alexdej

Reputation: 3781

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;
}

Upvotes: 20

jaywayco
jaywayco

Reputation: 6296

Try something like:

object o = this.GetType().GetCustomAttributes(true).ToList().FirstOrDefault(e => e is DataContractAttribute);

bool hasDataContractAttribute = (o != null);

Upvotes: 0

Related Questions