Click here to Skip to main content
15,895,084 members
Articles / Programming Languages / C# 4.0

New .NET Feature - Code Contracts

Rate me:
Please Sign up or sign in to vote.
3.44/5 (9 votes)
12 Aug 2009CPOL4 min read 32.8K   61   36  
Code Contracts provide a language-agnostic way to express coding assumptions in .NET programs
using System;
using System.Diagnostics.Contracts;
using System.Diagnostics; 

namespace CodeContracts
{
    class Program
    {
        static void Main()
        {
            CalculateWithDebugAssert cwda = new CalculateWithDebugAssert(4, 0);
            Console.WriteLine("Result is {0}", cwda.Divide());

            ClaculateWithContracts cc = new ClaculateWithContracts(4, 8);
            Console.WriteLine("Result is {0}", cc.Divide());
            
            Console.ReadLine(); 
        }
    }

    class CalculateWithDebugAssert
    {
        private int num1;
        private int num2;

        public CalculateWithDebugAssert(int numberone, int numbertwo)
        {
            num1 = numberone;
            num2 = numbertwo; 
        }

        public int Divide()
        {
            Debug.Assert(num2 > 0, "numbertwo should be greater than 0"); 
            if (num2 > 0)
                return num1 / num2;

            return num1;

        }
    }

    class ClaculateWithContracts
    {
        private int num1;
        private int num2;
      

        public ClaculateWithContracts(int numberone, int numbertwo)
        {
            num1 = numberone;
            num2 = numbertwo; 
        }

        [ContractInvariantMethod]
        protected void ObjectInvariant()
        {
            Contract.Invariant(this.num2>0);
        }

        public int Divide()
        {
            Contract.Ensures(Contract.Result<int>() > 0); 
            if (num2 > 0)
                return num1 / num2;

            return num1;

        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Wells Fargo
United States United States
MS Computer Science + Information Science
Architect at Wells Fargo [Wells Fargo Dealer Services -WFDS]
Blog: Profile

abhijit gadkari
abhijit dot gadkari at gmail dot com
Irvine-92618,CA

Comments and Discussions