Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

7.15 C# 6 Expression-Bodied Methods and Properties

6.jpg

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";
  • + Share This
  • 🔖 Save To Your Account