views:

28

answers:

2

Hi there,

I have just done some tests and i have manged to get ReadAsDataContract working on the Response.Content method...

The thing that really is confusing is that i thought it shouldn't work yet! As my classes are NOT decorated with the DataContact or DataMember Attributes.

I am confused, reading the various tutorials around the web it seems that it is IMPORTANT to decorate your class (used for ReadAsDataContract) with DataContract and DataMember attributes..

BUT mine is not and i put a breakpoint on the line that calls ReadAsDataContract and sure enough i have a LIST returned with the correct details. Here is the line

List<Models.Question> questions = response.Content.ReadAsDataContract<List<Models.Question>>();

Models.Question is not decorated with the attributes. I share my model assembly with both my server and my client.

Can somebody tell me why it works when as far as i know you need to add the attributes on the class and members (which i have not)

I am using Visual Studio 2010 and .NET 4 - ermmm i seem to remember that these attributes are no longer required - is this true??

Really look forward to any help.

I hate it when things WORK and they SHOULD NOT :-) but of course I also hate when this DON'T WORK when they SHOULD :-)

THanks!

+1  A: 

According to this all types can be serialized, not just ones with the DataContractAttribute.

Darrel Miller
Yes indeed it is .. thanks for the comment.
Martin
+2  A: 

Can somebody tell me why it works when as far as i know you need to add the attributes on the class and members (which i have not)

It seems the "burden" of putting [DataContract] on data classes and [DataMember] on each member to be serialized was too much for the programmers worldwide - so Microsoft changed the behavior of the DataContractSerializer in .NET 3.5 SP1.

Since that time, the DCS will behave like the old XmlSerializer with a class that isn't decorated - it will happily serialize all public members and properties.

Problem with that is, of course: you loose all the additional control that the attributes give you, like defining an XML namespace for your data contracts, defining the order of the data members etc. - but it works without adding any attributes.

So this is a known and willingly introduced behavior. I still believe you ought to be explicit in your intent and mark your data classes with [DataContract] and your members with [DataMember] (which also gives you the ability to ignore one or several public members and not include them in serialization).

marc_s
Thanks marc for a detailed explanation. Much appreciated
Martin