31. Fat arrows#

As you continue to write more complex code, you may find that conciseness can help keep your code readable and maintainable. One way to achieve this in C# is with “fat arrow” syntax which is more formally known as “expression-bodied members”. This feature provides a succinct syntax to express the implementation of local functions when their implementation consists of a single expression. It’s commonly referred to as “fat arrow” syntax due to the use of the => operator.

While we in this chapter will focus on using the fat arrow syntax with local functions, fat arrows can be used with class members such as methods, constructors, and properties. You will see examples of this later chapters.

Let’s consider a simple local function defined using the traditional method body:

int Add(int x, int y)
    return x + y;

We can simplify this function using the fat arrow syntax:

int Add(int x, int y) => x + y;

Here, the Add function is defined as an expression-bodied member. The => symbol points to the expression that becomes the function’s return value. Notice how we don’t need to explicitly use the keyword return. This version of Add is functionally identical to the previous one but is shorter and cleaner. Fat arrows are essentially syntactic sugar.

Remember, expression-bodied members aren’t limited to local functions - they can be used with instance methods, constructors, and properties. We will see usage of fat arrows in these contexts in the future but won’t explain it in any more detail than we’ve done here. So do come back to this chapter if you need a refresher.

This chapter should give you a good understanding of how the fat arrow syntax can help you write more concise and readable code. Embrace the power of expression-bodied members and make your code fast to write and easier to read.