Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Code Contracts
Message
From
21/08/2011 13:03:47
 
 
To
21/08/2011 12:40:59
General information
Forum:
ASP.NET
Category:
Other
Title:
Environment versions
Environment:
C# 4.0
Miscellaneous
Thread ID:
01521429
Message ID:
01521432
Views:
55
Likes (1)
>>I'm looking at the code contracts library included in .NET 4
>>Anyone using this regularly and/or have opinions ?
>>I'm currently working with VS Pro so, whilst I can see some benefit in the runtime checks, it seems to me that I'm missing the most useful facet (i.e. static checking).....
>
>Where is that exactly? I never heard of that before.

Basically (but oversimplified) a replacement for asserts or other parameter checking. For example you might currently have code such as (C# I'm afraid but you will get the jist):
public int ProcessInvoice(EdifactInvoice invoice)
        {
            if (invoice == null)
                throw new NullReferenceException("Invoice cannot be null");

            //Elided
            return 5;
        }
Using code contracts you can refactor this to:
public int ProcessInvoice(EdifactInvoice invoice)
        {
            Contract.Requires<NullReferenceException>(invoice != null);
            Contract.Ensures(Contract.Result<int>() > 0);
            //Elided
            return 5;
        }
The 'Contract.Requires' serves the same purpose as the original null check at runtime - but with versions higher than VS Pro will *also* catch any existing call to the method which might fail to fullfill the 'contract at compile time. The Contract.Ensures line will, in this non-realistic example, also throw an exception if the return value does not meet the condition. A neat thing with the latter is that it will do this even if there are multiple return paths.....

Here's a link to an overview: http://research.microsoft.com/en-us/projects/contracts/
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform