Expression Bodied Members For Properties and Indexers in C# 6.0

In one of the earlier post blogged under new features in C# 6.0, we saw how we can make use of the Expression bodied functions to get rid of the one liner functions to increase the readability and maintainability of the code. Likewise we can also create expression bodied methods for properties instead of the classic getter method. For example let’s take a note of code given below which is using the classic way of creating and initializing the property.

Here we have a readonly property called FullName for which value is created by concactnating FirstName and LastName property in the getter method.

As you saw in the earlier post we can make use of the lambda arrow(=>) instead of the code block enclosed in curly braces({}) to define the body of the getter method. The syntax is pretty straightforward

property name => expression

So let’s see how can we make use of the expression bodied member for our FullName property from the earlier example.

The FullName property is a read only property even though we haven’t used the get keyword for that. By implementing the expression bodied syntax for the property, the compiler will treat it as a read only all the time. If you compare the two examples side by side, you can easily make it visually that our code in much simpler, leaner and readable when we made use of expression bodied syntax.

So you may be wondering now that whether the approach of using Expression Bodied members for properties has got any performance implications. Actually it doesn’t have any because it’s simply a syntactical sugar for the first example we covered and if we examine the generated IL for both these approaches, it will be the same.

Apart from using it with properties, we can also make use of the expression bodied members for indexers also as shown in the example below.

No Comments

Add a Comment