by luisabreu via LA.NET [EN] on 4/7/2010 8:44:31 AM
Oh well…remember my last post…the happiness of getting everything working out…Well, unfortunately, things stopped working (read: code contract started generating exceptions) when you define more than one invariant. Here’s my initial code:
public class Dumb { public String A { get; set; } public String B { get; set; } public Dumb() { Initialize(); } [OnDeserializing] private void DeserializerHelper() { Initialize(); } private void Initialize() { A = B = ""; } [ContractInvariantMethod] private void Invariants() { Contract.Invariant( A != null); Contract.Invariant( B != null); } }
When you use code contracts and configure it so that it’s also used at runtime, you’ll start getting exceptions when an instance of Dumb is deserialized. The problem here is that setting B to “” will end up checking the object’s invariants and that means that A is still null (and there you go: an exception). The only workaround for this is using backing fields for each property and changing the initialization code so that it uses those new backing fields (instead of going through the properties). I guess you could always dismiss code contracts on objects that are used by WCF services, but that seems worst than using backing fields…
Original Post: The OnDeserializingAttribute – part II
The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.