Clone wiki

NContracts / Home

Welcome

NContract is a library to help writing argument verifications check and trhrow logic without having to specify the argument name as a literal string. Let's see an example showing how to use it:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NContracts
{
    public class Demo
    {
        /// <summary>
        /// Classical not null verification
        /// </summary>
        /// <param name="arg1"></param>
        public void DoSomething(string arg1)
        {
            Contract.Expect(() => arg1).IsNotNull();
        }

        /// <summary>
        /// Classical not null verification, with custom 
        /// exception and message
        /// </summary>
        /// <param name="arg1"></param>
        public void DoSomethingWithCustomMessage(string arg1)
        {
            Contract.Expect(() => arg1)
                .Throw((n)=>new Exception(string.Format("I'm unhappy to see that {0} is null",n)))
                .WhenViolate
                .IsNotNull();
        }

        /// <summary>
        /// Asserting an argument greather than another
        /// </summary>
        /// <param name="min"></param>
        /// <param name="max"></param>
        public void DoSomething(int min,int max)
        {
            Contract.Expect(() => min)
                .IsLessThan(int.MaxValue)
                .Meet(a => a <= max);
        }
        /// <summary>
        /// Validate an integer argument in a certain range
        /// </summary>
        /// <param name="arg1"></param>
        public void DoSomething(int arg1)
        {
            Contract.Expect(() => arg1).IsGreatherThan(0)
                                       .IsLessThan(100);
                ;
           
        }
        /// <summary>
        /// Validate an array in length and asserts first element should be zero
        /// </summary>
        /// <param name="array"></param>
        public void DoSomething(int[] array)
        {
            Contract.Expect(() => array).Meet(a => a.Length > 0 && a.First() == 0);
        }
       
    }
}

Updated