;
vote buttons
13
18 Feb 2015 by K Bonneau

C# 6 Expression Bodied Methods & Properties

c#

What are Expression Bodied Methods / Properties?

This is a new syntax introduced in C# 6, which helps you write simple one-liner functions and readonly properties without explicit return types and curly braces. Look at the sample below:


Are these lambda expressions?

No these aren't lambda expressions, though the syntax is very similar. Let's see what IL the following function generates:

public double Square(double x) => x * x;
.method public hidebysig instance float64 
        Square(float64 x) cil managed
{
  // Code size       4 (0x4)
  .maxstack  8
  IL_0000:  ldarg.1
  IL_0001:  dup
  IL_0002:  mul
  IL_0003:  ret
} // end of method Program::Square


Now lets compare the IL with similar function without using expressions
public double Square(double x)
{
  return x * x;
}
.method public hidebysig instance float64 
        Square(float64 x) cil managed
{
  // Code size       4 (0x4)
  .maxstack  8
  IL_0000:  ldarg.1
  IL_0001:  dup
  IL_0002:  mul
  IL_0003:  ret
} // end of method Program::Square

Its exactly the same. So the compiler just expands expression bodied members to its full form. Nothing new here. Just some compiler magic. This also indicates that there are no performance implications with expression bodied members.

Note that you cannot use expression bodied members for void returning functions (that includes constructors) and read/write properties. It can be used for functions with return values, read-only properties and indexers.

So it's just some syntactic sugar?

Yes, but that's not necessarily a bad thing. It requires less typing and makes your code more concise and readable. These dont look so useful at first glance, as this is not something we are used to yet, but eventually they would come across as more natural. Imagine life without yield, using, var, ?, ??.. too bland & not much fun, right?

Related: Try the new C# 6 Features Online


Comments