Chapter 14. Concise code in C# 7

 

This chapter covers

  • Declaring methods within methods
  • Simplifying calls by using out parameters
  • Writing numeric literals more readably
  • Using throw as an expression
  • Using default literals

C# 7 comes with large features that change the way we approach code: tuples, deconstruction, and patterns. It comes with complex but effective features that are squarely aimed at high-performance scenarios. It also comes with a set of small features that just make life a little bit more pleasant. There’s no single feature in this chapter that’s earth-shattering; each makes a small difference, and the combination of all of them can lead to beautifully concise, clear code.

14.1. Local methods

If this weren’t C# in Depth, this section would be short indeed; you can write methods within methods. There’s more to it than that, of course, but let’s start with a simple example. The following listing shows a simple local method within a regular Main method. The local method prints and then increments a local variable declared within Main, demonstrating that variable capture works with local methods.

14.2. Out variables

14.3. Improvements to numeric literals

14.4. Throw expressions

14.5. Default literals (C# 7.1)

14.6. Nontrailing named arguments (C# 7.2)

14.7. Private protected access (C# 7.2)

14.8. Minor improvements in C# 7.3

Summary