Search code examples
c#code-contractsinvariants

code skips over Contract.Requires


I'm trying to write this method using c# contracts...but when debugging, it completely ignores the Contract.requires and CheckRep() Am I using this incorrectly??

    public Poly Add(Poly q)
    {
        CheckRep();
        Contract.Requires(q != null, "You need to provide a valid non-null Poly.");

        Poly la, sm;

        if (deg > q.deg)
        {
            la = this; sm = q;
        }
        else
        {
            la = q; sm = this;
        }

        int newdeg = la.deg;

        if (deg == q.deg)
        {
            for (int k = deg; k > 0; k--)
            {
                if (trms[k] + q.trms[k] != 0)
                {
                    break;
                }
                else
                {
                    newdeg--;
                }
            }
        }

        Poly r = new Poly(newdeg);

        int i;

        for (i = 0; i <= sm.deg && i <= newdeg; i++)
        {
            r.trms[i] = sm.trms[i] + la.trms[i];
        }
        for (int j = i; j <= newdeg; j++)
        {
            r.trms[j] = la.trms[j];
        }

        return r;
    }

Solution

  • It has to be:

      public Poly Add(Poly q)
        {
            Contract.Requires(q != null, "You need to provide a valid non-null Poly.");
            CheckRep();
    

    From MSDN:

    1. This method call must be at the beginning of a method or property, before any other code.

    2. This contract is exposed to clients; therefore, it must only reference members that are at least as visible as the enclosing method.

    3. Use this method instead of the Contract.Requires(Boolean, String) method when you want to throw an exception if the precondition fails.

    You also have to activate runtime checking. Right click on your project->properties. Click "Code Contracts" in the left hand menu. Check "Perfrom Runtime Contact Checking"