Chapter 10. A smörgåsbord of features for concise code
This chapter covers
- Avoiding code clutter when referring to static members
- Being more selective in importing extension methods
- Using extension methods in collection initializers
- Using indexers in object initializers
- Writing far fewer explicit null checks
- Catching only exceptions you’re really interested in
This chapter is a grab bag of features. No particular theme runs through it besides expressing your code’s intention in ever leaner ways. The features in this chapter are the ones left over when all the obvious ways of grouping features have been used. That doesn’t in any way undermine their usefulness, however.
The first feature we’ll look at provides a simpler way of referring to static members of a type, including extension methods.
The canonical example for this feature is System.Math, which is a static class and so has only static members. You’re going to write a method that converts from polar coordinates (an angle and a distance) to Cartesian coordinates (the familiar (x, y) model) using the more human-friendly degrees instead of radians to express the angle. Figure 10.1 gives a concrete example of how a single point is represented in both coordinate systems. Don’t worry if you’re not totally comfortable with the math part of this; it’s just an example that uses a lot of static members in a short piece of code.