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# 4.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.