Asserts and Contracts

Statically discovering typical code defects is a big convenience, but it isn’t a silver bullet. Lots of conditions are intrinsic to the algorithms you’re coding up and simply cannot be detected by tools without particular knowledge of the developer’s intent.

To communicate intent, various mechanisms have been created over the years. The oldest and simplest one is to use asserts, which are pieces of code that perform a logical check, typically only in special builds of your software. If the check fails, the developer is notified and invited to break in the debugger to analyze what’s going wrong. Maybe the condition makes a false assumption about code invariants, or you’ve just caught a problem on the spot before it can do ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.