Expression Bodied Methods in C# 6.0

As developers we have created functions with a single statement that just return trivial values or expressions. Expression bodied function helps us to make our code more readable and concise. Normally we do write functions with statements being surrounded by curly braces be it for single line or for multiple lines of code. A typical example is given below

In C# 6.0, it’s now possible to write function bodies as lambda expression. We will make use of the lambda arrow(=>) instead of the curly braces({}). So we will see how we can transform the earlier code to make use of the expression bodied functions.

A expression bodied function must include  a name for the function, the return type of the function and the returned expression itself.

Syntax : method signature => expression

There are some important limitation with Expression bodied functions

1. Block statements are not allowed inside Expression bodied functions

2. Branching statements are not allowed such as if,else and switch

3. Expression bodied functions are not a replacement for switch statements

4. Loop statements such as for, foreach, while and do are also restricted.

5. Constructors or finalizers are also restricted

One of the main advantage of using expression bodied functions increases the readabilty of the code. Even though they are short, it conveys the intentions clearly. Also we can avoid extra text which reduces the memory footprint also.

So whenever you come across the need for creating a function with single statement, don’t hesitate to implement expression bodied function there. Please take a note that it’s C# 6.0 only feature.

Note : You may have noticed that I have used a $ symbol and used the members directly inside the string literal itself in the Console.WriteLine statement. That's the new string interpolation operation in C# 6.0 and you can read more about it here.

No Comments

Add a Comment