Chapter 13. Improving efficiency with more pass by reference

 

This chapter covers

  • Aliasing variables with the ref keyword
  • Returning variables by reference with ref returns
  • Efficient argument passing with in parameters
  • Preventing data changes with read-only ref returns, read-only ref locals, and read-only struct declarations
  • Extension methods with in or ref targets
  • Ref-like structs and Span<T>

When C# 7.0 came out, it had a couple of features that struck me as slightly odd: ref local variables and ref returns. I was slightly skeptical about how many developers would need them, as they seemed to be targeted situations involving large value types, which are rare. My expectation was that only near-real-time services and games would find these useful.

C# 7.2 brought another raft of ref-related features: in parameters, read-only ref locals and returns, read-only structs, and ref-like structs. These were complementary to the 7.0 features but still appeared to be making the language more complicated for the benefit of a small set of users.

I’m now convinced that although many developers may not directly see more ref-based code in their projects, they’ll reap the benefits of the features existing because more-efficient facilities are being made available in the framework. At the time of writing, it’s too early to say for sure how revolutionary this will prove, but I think it’s likely to be significant.

13.1. Recap: What do you know about ref?

13.2. Ref locals and ref returns

13.3. in parameters (C# 7.2)

13.4. Declaring structs as readonly (C# 7.2)

13.5. Extension methods with ref or in parameters (C# 7.2)

13.6. Ref-like structs (C# 7.2)

Summary