Search code examples
exceptioncode-contracts

ArgumentNullException Vs Contract.Requires


The ArgumentNullException throws an exception if the argument that is passed to it is null. This happens at the runtime. What does Contract.Requires do? Is it a compile time checking or checked at runtime?


Solution

  • Contract.Requires is a runtime check (the runtime checks are automatically generated at compile time - see chapters 6.2 and 7 of the documentation). There are also certain static checks that can be performed (see chapter 6.6 of the documentation), but Requires is a runtime check.

    Note that there is a generic overload that'll let you specify the exception that you want thrown (eg, ArgumentNullException)