Expression-bodied members in C#

gpeipman
2,169 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Expression-bodied members

C# supports expression-bodied members that allow us to write more compact code by using expressions directly instead of wrapping them into properties. To get better idea about expression-bodied members take a look at the following code sample where Distance is expression-bodied member.

public double A { get; set; }
public double B { get; set; }
 
public double Distance => Math.Sqrt(X * X + Y * Y);

Expression-bodied members in action

Now let's see some real stuff where expression-bodied members can be of great help. Here is the InvoiceLine class with some properties that perform calculations.

We can turn calculating properties to expression-bodied members like show below.

Client code that uses InvoiceLine class doesn't need any changes due to this change in InvoiceLine class

foreach(var line in invoice.Lines)
{
    invoiceTotal += line.Total;
}

Using expressions with arguments

Expression-bodied members can be also expressions with arguments like shown in following example. There is simple task with worklogs collection. Collection is initialized when class is created and after this some worklogs are added to task. Then time spent on task today and yesterday is calculated.

Be careful with more complex expression-bodied members and make sure they don't grow too big and doesn't form bad mess or spaghetti code.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content