Microsoft has recently revamped what was previously their Reference Source Code Center to be simply Reference Source. This is a site for .NET developers who are interested in viewing the source code for the platform API’s, and like the Java OpenJDK this provides a wealth of learning opportunities for .NET. While I have spent only a few hours going through some of the code, there are definitely some common themes that are worth noting and at the top of my list is design by contract.

Design by Contract (DBC) is now integral to the .NET platform as part of System.Diagnostics.Contracts. Using DBC, developers express pre and post conditions for method invocations. For example, if you are converting a string for output you may want to ensure that the string itself is not null and the output returned is not null either.

You can certainly perform these kinds of checks directly in your code, or with a contract you can assert what conditions you are expecting for the data you are manipulating. For example, if you were dealing with a phone number input/output you could verify you received data in that format. To enable contract validation at runtime, you must also install Code Contracts for .NET. The process of configuring contract validation is then a property of your Visual Studio Project, it may be something you only want to enable for debug purposes.

Code Contract Exception

The exciting part of DBC is that it is now integral to the .NET code base. For example, the Concat() operation of String does contract validation to ensure a non-null String reference is returned in all cases. While previously you may have thought of DBC as an academic exercise, clearly Microsoft is taking this seriously and this means your code should probably start using this as well.

A few other things worth noting:

  • Lots of conditional includes for SilverLight. For example, if SILVERLIGHT is defined then serialization is an attribute; otherwise, it just extends Serializable. It seems like this platform should either align with what .NET is doing or be deprecated.
  • Native methods are leveraged when necessary. For example, when adding an entry to the end of an ArrayList this is simply an array of Object[], and if adding to the end of the list then it increments the max index and puts it into the array at that point. If you’re doing file I/O, however, then native methods are used to read and write.
  • Filenames for classes tend to be lowercase, despite the fact that the classes themselves start with an uppercase letter.
  • Some methods are prefixed with a double-slash “//” comment block while some are triple-slashed “///”. I’ve always used the latter with C# but maybe I should revisit that.