- 7.1 Introduction
- 7.2 Packaging Code in C#
- 7.3 static Methods, static Variables and Class Math
- 7.4 Methods with Multiple Parameters
- 7.5 Notes on Using Methods
- 7.6 Argument Promotion and Casting
- 7.7 The .NET Framework Class Library
- 7.8 Case Study: Random-Number Generation
- 7.9 Case Study: A Game of Chance; Introducing Enumerations
- 7.10 Scope of Declarations
- 7.11 Method-Call Stack and Activation Records
- 7.12 Method Overloading
- 7.13 Optional Parameters
- 7.14 Named Parameters
- 7.15 C# 6 Expression-Bodied Methods and Properties
- 7.16 Recursion
- 7.17 Value Types vs. Reference Types
- 7.18 Passing Arguments By Value and By Reference
- 7.19 Wrap-Up
7.15 C# 6 Expression-Bodied Methods and Properties
C# 6 introduces a new concise syntax for:
methods that contain only a return statement that returns a value
read-only properties in which the get accessor contains only a return statement
methods that contain single statement bodies.
Consider the following Cube method:
static int Cube(int x) { return x * x * x; }
In C# 6, this can be expressed with an expression-bodied method as
static int Cube(int x) => x * x * x;
The value of x * x * x is returned to Cube’s caller implicitly. The symbol => follows the method’s parameter list and introduces the method’s body—no braces or return statement are required and this can be used with static and non-static methods alike. If the expression to the right of => does not have a value (e.g., a call to a method that returns void), the expression-bodied method must return void. Similarly, a read-only property can be implemented as an expression-bodied property. The following reimplements the IsNoFaultState property in Fig. 6.11 to return the result of a logical expression:
public bool IsNoFaultState => State == "MA" || State == "NJ" || State == "NY" || State == "PA";