Should CodeContracts replace regular ArgumentExceptions?

Is it possible to use CodeContracts instead:

if (XXX == Y)
    throw new ArgumentException("bla bla");

How does it work if I create a library and my library users do not use CodeContracts?

+3
source share
3 answers

Assuming that code using code contracts is executed via binary rewriting, it will throw exceptions, such as the code you posted. The repeater reviews the code and replaces the contract code with argument checking, etc. This is similar to aspect-oriented programming. It enters a code to handle situations for you after you compile it.

, , , .

+2

:

Contract.Requires<ArgumentNullException>(argumentToCheck, "argumentToCheck");

, , , ArgumentNullException.

ArgumentNullException , , , .

+1

, 2 , :

  • check/entry point return value/exit point assertion.

, .

: throw ArgumentException.

ArgumentException - , , , .

There is much more going on with Code Contracts, but I just dipped my sock and I don’t have a version that does super-comprehensive static checks. I plan to work more on using Code Contracts, and as soon as I do, it will be more elegant to check the parameters using the same structure instead of switching between code contracts and if / then / throw ArgumentException

0
source

Source: https://habr.com/ru/post/1781248/


All Articles