Monday, June 28, 2010

Code Contracts: don't forget to turn them on

dd491992_codecontracts_project(en-us)

If you use the new System.Diagnostics.Contracts classes like

int Div(int a, int b)
{
  Contract.Requires(b > 0);
  return a / b;
}

Do not forget to download the Code Contracts tool and turn on static and/or runtime checking of your code.

Otherwise the Contract.Requires statement above will just be ignored (thus the second parameter will not be checked)…

Notes:

  • If you use Contract.Requires<TException> you will receive an assert message telling you that you need to use the rewriter
    image
  • Alternatively, leave your pre-conditions as old-fashoned if-then-throw-statements, and end them with EndContractBlock, (contract tools recognize them as legacy-require statements).
    Beispiel aus den FAQs:

    void MyMethod(Foo foo)
    {
       if (foo == null) throw new ArgumentNullException(...);
       Contract.EndContractBlock();
       ... normal method code ...
    }

No comments: