Menu

C# 6 features: Expression-bodied members

June 5, 2015 - .NET, C#, Programming

This is part of a series of posts covering new C# 6 features. Currently there are posts covering the following:
String Interpolation
Expression-bodied Members
Improved Overload resolution
The Null Conditional operator
Auto-Property Initializers


In my Previous Post I discussed the new String Interpolation feature of C#. Today, I will be covering another C# 6 feature called “Expression-bodied members”.

Functions- the basic form of a method- are not a new programming concept by any means, and widespread use of functions helped progress the landscape of software development by allowing segments of code to be more compartmentalized from the rest of the program. Many of the earlier implementations or basic implementations (no pun intended) didn’t support multiple-lined functions, but you could define functions in a single line declaration. One example being many dialects of BASIC which had the DEF FN feature:

you could declare a function definition, with a single expression, and then use that function in your BASIC code. In some sense, C#’s “expression bodied member” feature provides you with this brevity.

One summary of the feature could be to say that it is effectively giving you the ability to declare member methods in a class by using lambda-style syntax. Consider our previous example code, which included a method in our test class:

This is a very straightforward method that merely increments a field. We could define this as an Expression-bodied member like so:

This is a very useful feature because it allows for the definition of very basic functions in a very straightforward manner. One arguably disadvantage is that if those functions need to be expanded, than they need to be reworked into the “standard” function form, rather than using the expression-bodied syntax. Excepting large, bulk changes, however, I don’t think that is a serious detriment to the feature, and when dealing with a large set of very basic helper functions, this syntax can make the code much shorter and easier to read, in general (and remove “redundant” return statements, as well.

It is of course possible to define a void method in this manner- in that case, the expression body needs to be a statement. This can be fairly useful when you have transformative methods which effectively call another method with different arguments, which could include overloads as well as methods that delegate to a composition class instance. It is notable that it cannot be used to define constructors. The logic behind the design being stated as being because constructors have specific structures and syntax around their declaration and the use of the fat-arrow makes it more difficult to parse (both for people and the compiler) and the feature is most useful for functions which return a result anyway, rather than side-effecting methods.

Have something to say about this post? Comment!