The OnDeserializingAttribute – part II

Published Wed, Apr 7 2010 9:44

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…

Filed under: , ,

Comments

# LA.NET [EN] said on Monday, July 12, 2010 4:14 AM

When we create a new type and define a constructor, I guess there’s nothing wrong with expecting to see

# LA.NET [EN] said on Monday, July 12, 2010 4:16 AM

When we create a new type and define a constructor, I guess there’s nothing wrong with expecting to see

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above:  

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Silverlight 4.0: Curso Completo

    ASP.NET 4.0: Curso Completo

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover