How to find out if class has DataContract attribute?
Asked Answered
S

4

15

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!

Spout answered 18/7, 2011 at 14:25 Comment(0)
S
20

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;
}
Second answered 18/7, 2011 at 14:35 Comment(2)
Set this answer as accepted because I don't have to get all attributes.Spout
I could only get the second example to compile using an InvalidDataContractException.Larissa
F
7
    bool hasDataContractAttribute = typeof(YourType)
         .GetCustomAttributes(typeof(DataContractAttribute), true).Any();
Flagrant answered 18/7, 2011 at 14:28 Comment(2)
Nice answer. In LINQ, it's generally better to use Any() than Count() > 0 for both performance and readability, but in this case it's an academic distinction.Rota
If you have an object of the class, better to replace typeof(YourType) with this.GetType()Zygoma
C
0

Try something like:

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

bool hasDataContractAttribute = (o != null);
Circle answered 18/7, 2011 at 14:31 Comment(0)
W
0

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;
Willywillynilly answered 16/4, 2013 at 13:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.