Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 773
Alex Avatar asked Jul 18 '11 14:07

Alex


People also ask

How do you determine if a class has a particular attribute?

The same you would normally check for an attribute on a class. Here's some sample code. typeof(ScheduleController) . IsDefined(typeof(SubControllerActionToViewDataAttribute), false);

What is DataContract attribute?

[DataContract] attribute specifies the data, which is to serialize (in short conversion of structured data into some format like Binary, XML etc.) and deserialize(opposite of serialization) in order to exchange between the client and the Service.

What is DataContract in C#?

A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. That is, to communicate, the client and the service do not have to share the same types, only the same data contracts.

What is use of DataMember attribute in C#?

Data Member are the fields or properties of your Data Contract class. You must specify [DataMember] attribute on the property or the field of your Data Contract class to identify it as a Data Member. DataContractSerializer will serialize only those members, which are annotated by [DataMemeber] attribute.


1 Answers

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;
}
like image 148
alexdej Avatar answered Sep 21 '22 00:09

alexdej