Throwing exceptions upon detecting a bad or unexpected value is good programming practice called precondition checking. However, writing the same checks over and over in different areas of the code base is tedious, error prone, and difficult to maintain.
PostSharp Code Contracts have the following features and benefits:
More readable. PostSharp Code Contracts are represented as custom attributes there is less code to read and understand.
Inherited. You can add a PostSharp Code Contract attribute to an interface method parameter and it will automatically be enforced in all implementations of this method.
Localizable. It's easy to display the error message in the user's language, even if you didn't design for this scenario upfront.
In this chapter
|Adding Contracts to Code
|This section demonstrates how to add contracts to code and how inheritance works.
|Creating Custom Contracts
|This section explains how to create your own contract attributes.
|Customizing Contract Exceptions
|This section explains how to replace the default exception types by your own.
|Localizing Contract Error Messages
|This section describes how to customize the texts of exceptions that are thrown when a contract is violated.