You may be surprised to find that classes are serialized by WCF without any [DataContract]
attribute attached to them. I certainly was!
When WCF came out, there was much fanfare of the new, improved, superior WCF serializer (justified IMHO). The main policy sizzle was that unlike the [Serializable]
marking a POCO object and then [NonSerialized]
attribute marking specific fields (opt-out), WCF will now use “opt-in”: Only properties specifically decorated will be serialized.
This serialization policy was clearly expressed, and the side effect of it all is that suddenly I have a bunch of projects that fail some unit tests. Upon digging, I found that SP1 has introduced a new kink: if you don’t decorate your class at all (omit / not add the [DataContract]
attribute) then the object becomes “fully” serializable by WCF. All public properties will be automatically included.
This may seem as a huge step back to those that relied on the opt-in feature to hide certain classes from the serializer. This also may be a huge sigh of relief to those who cringed at the effort of (re)decorating all their message and value objects for WCF.
Note that now with SP1, if you do decorate an object with [DataContract]
then the old rules apply - only properties with [DataMember]
will be serialized. So to be selective, you may still decorate with [DataContract]
and then selectively decorate only the properties you want.
I don’t know what led to the exact decision, and the syntax nuance definitely walks a fine line. One could argue that classes without decoration now serialize without effort, but ones marked for WCF specifically still behave as previously advertised.
All in all, 2 hours of head scratching in disbelief, 1 hour to change some unit test expectations, not too awful. Long live refactoring tools in Visual Studio!