Chapter 14 Concise Code In Csharp 7

2 min read
Rapid overview

Chapter 14 — Concise code in C# 7

Purpose of this chapter: cover the “small but everywhere” features in C# 7.x that reduce boilerplate while keeping code explicit: local functions, out vars, numeric literal improvements, throw expressions, default literals, named argument flexibility, and access/constraint tweaks.


14.1 Local functions (local methods)

Local functions let you define helper methods inside a method:

  • Often better than lambdas when you want clear control flow, recursion, or to avoid allocations.

Guidelines:

  • Use to keep a helper close to where it’s used.
  • Keep them short; if they grow, extract to a private method.

14.2 Out variables

Inline declarations reduce ceremony:

if (int.TryParse(text, out var value)) { /* use value */ }

Interview nuance:

  • Know the scoping rules (where the out var is in scope) and avoid using it too broadly.

14.3 Improvements to numeric literals

14.3.1 Binary integer literals

Binary literals can make bit flags easier to read.

14.3.2 Underscore separators

_ separators improve readability for large numbers:

  • Great for money/time constants and bit masks.

14.4 Throw expressions

Throw can be used in expressions:

  • Useful with null-coalescing and conditional expressions.

Guideline:

  • Keep it readable; don’t turn it into a clever one-liner that hides behavior.

14.5 Default literals (C# 7.1)

default can be used without an explicit type in context:

  • Reduces noise when the type is obvious from the assignment/parameter type.

14.6 Nontrailing named arguments (C# 7.2)

You can mix positional and named args more flexibly.

Guideline:

  • Use named arguments for readability, but keep call sites consistent and avoid confusing mixes.

14.7 Private protected access (C# 7.2)

private protected is for members accessible:

  • In the containing type, or in derived types within the same assembly.

Interview use case:

  • Useful for frameworks where you want to allow inheritance inside the assembly but not outside.

14.8 Minor improvements in C# 7.3

14.8.1 Generic constraints

Constraints became more expressive (especially for value-type scenarios).

14.8.2 Overload resolution improvements

These reduce surprising ambiguities; interviewers may ask about overload resolution pain points.

14.8.3 Attributes for backing fields of auto-properties

Improves interop/serialization scenarios where attributes need to target the generated backing field.