Home > Articles > Programming > C#

C# 6: Expression Bodied Members Simplify Your Code

In a series of articles, Bill Wagner, author of Effective C#: 50 Specific Ways to Improve Your C#, Second Edition, explores some of the powerful new features in Visual Studio 2015 that will soon become familiar friends. This article discusses how to simplify your C# code with the precise syntax of expression bodied members, saving time, keystrokes, and processor overhead.
Like this article? We recommend

Introduction

Expression bodied members are one of the fundamental new features in C# 6.0. In addition to being useful in their own right, they provide core syntax for other features that I will cover later in this series. Expression bodied members enable developers to create clear representations of their designs in a concise syntax. In this article, I'll define the syntax for the feature, explain its use and limitations, and give some initial guidance on using this feature. This guidance is preliminary, however, because the expression bodied members feature is new, and the community has had a limited time to use it.

Syntax for Expression Bodied Members

The syntax for method-like expression bodied members is a natural combination of the current syntax for members and the lambda expression syntax. Let's begin with expression bodied members that represent methods. In the same way that lambda expressions provide a concise way to define delegate types, expression bodied members are a concise way to define a method. Instead of a block body surrounded by curly braces ({ }), you use the lambda arrow (=>). The expression to the right of the lambda arrow represents the body of the method. For example, these two methods are essentially the same:

public int DoubleTheValue(int someValue)
{
    return someValue * 2;
}

public int DoubleTheValue(int someValue) => someValue * 2;

That's the basics. An expression bodied member is very similar to an anonymous lambda expression, but the expression bodied member must include a name, the return type, and returned expression.

Several other optional modifiers can be applied to the member method declaration:

  • Methods can specify accessibility: public, protected, internal, private, and even protected internal.
  • Methods can be declared virtual or abstract, or might override a base class method.
  • Methods can be static.
  • Methods can implement specialized behavior for many operators, including explicit and implicit conversion operators.
  • Methods can be asynchronous if they return void, Task, or Task<T>.

Almost all of these modifiers are allowed in methods declared with expression bodied members. The only exception is abstract methods, which cannot declare a body; it follows that they cannot include a body defined using an expression bodied member.

Expression Bodied Members for Properties and Indexers

The syntax for expression bodied members must take into account the more nuanced syntax for properties and indexers. When you define read/write properties or indexers, you create two methods: a getter method and a setter method. No clear syntax exists for creating both methods using expression bodied members. Expression bodied members on properties are limited to read-only properties and indexers. The right side of the lambda arrow contains the body of the get method; the nested braces and the get keyword are omitted. For example, this property accessor returns the time when an object was created:

public DateTime CreatedTime => timestamp;

Is equivalent to:

public DateTime CreatedTime
{
    get
    {
        return timestamp;
    }
}

The lambda arrow simplifies the declaration of a read-only property or an indexer. It also forms the basis for getter-only auto properties and auto property initializers.

Limitations on Expression Bodied Members

Even if you wanted to do so, you probably couldn't replace every member declaration with an equivalent expression bodied member declaration. There are a number of limitations on where you can use expression bodied members. I've already discussed the limitation on property setters.

The most important limitation is that block statements are not allowed. That may sound like a significant limitation, but in practice it isn't. If you need multiple statements in your method, you should simply use the existing syntax for defining that member.

Some statements are not allowed in expression bodied members. One such class of statements is the branching statements: if, else, and switch. For simple cases, the conditional operator (also referred to as the ternary operator) can suffice. For example, both of these two methods perform the same operation:

public override string ToString()
{
    if (middleName != null)
    {
        return firsName + " " + middleName + " " + lastName;
    } else
    {
        return firstName + " " + lastName;
    }
}

public override string ToString() =>
    (middleName != null)
    ? firstName + " " + middleName + " " + lastName
    : firstName + " " + lastName;

Expression bodied members offer no natural replacement for the switch statement. If you're using switch statements in your method, in most cases you shouldn't use expression bodied members.

The other class of statements prohibited in expression bodied members is loop statements: for, foreach, while, and do. In some instances, these constructs can be managed using LINQ queries. As a simple example, these two methods will return the same sequence:

public IEnumerable<int> SmallNumbers()
{
    for (int i = 0; i < 10; i++)
        yield return i;
}

public IEnumerable<int> SmallNumbers() => from n in Enumerable.Range(0, 10)
                                            select n;

In addition to the statement limitations, you cannot create constructors or finalizers using the expression bodied member syntax.

Finally, you can create async members using the expression bodied member syntax (with a little guidance, which I provide in the next section). When you add the async modifier, you can use the await expression in members declared using expression bodied members. However, in practice, I've rarely declared async expression bodied members. Async methods usually are not single-line methods that call other task-returning methods. In cases where they are, it's often preferable to create a method that returns a task, without adding the async modifier. For example, consider this (somewhat contrived and trivial) example:

public async Task<string> ReadFromWeb() => await RunWebRequest();

The compiler is performing some heavy lifting to implement the async state machine for this method. Because of the structure of the method, that extra work isn't really accomplishing much. It's creating a state machine to wrap a task that simply unwraps a task returned from a different method. Instead, you might write this construct as follows:

public Task<string> ReadFromWebSimple() => RunWebRequest();

It's still rather trivial, but now the compiler doesn't need to create the extra state machine to await and unwrap the constituent task. I rarely create meaningful one-line async methods. However, the feature does support them.

Some Initial Guidance on Using Expression Bodied Members

Let's begin with a disclaimer: These are new features. As I write this, Visual Studio 2015 RC is the current release. The global community has worked with only a few prerelease builds, and things may change. My suggestions will likely change as we all get more experience with these new features.

Expression bodied members should help you to create more readable code. The expressions are more concise, yet very readable. The extra text removed by transforming a traditional method into an expression bodied member is largely ceremonial and rarely contributes to the overall semantic understanding of the method. For that reason, I've been using the expression bodied member syntax for any methods that contain a single statement in their implementation. This change simplifies the class, making it more concise. It's easy to read and skim as I'm developing an application.

I balance that possibility with the fact that trying to put too much logic into a single statement, while often possible, can create less-readable code. If I find I'm massaging the implementation of a member in order to use a single statement, I'll avoid using the expression bodied member syntax.

Overall, I use the expression bodied member syntax when conciseness makes the overall design more clear. In those cases where using an expression bodied member makes a less readable method, I use the classic syntax. As an example, look at the following two versions of a complex number type. One uses the classic syntax. The other includes the expression bodied member syntax. I've made the design decision that the Complex class should be immutable type. Once you construct a complex number, it doesn't change.

public class ComplexNumber
{
    private readonly double realPart;
    private readonly double imaginaryPart;

    public ComplexNumber(double real, double imag)
    {
        this.realPart = real;
        this.imaginaryPart = imag;
    }

    public double Magnitude
    {
        get
        {
            return Math.Sqrt(realPart * realPart + imaginaryPart * imaginaryPart);
        }
    }

    public override string ToString()
    {
        return string.Format("{0}, {1}", realPart, imaginaryPart);
    }

    public static ComplexNumber operator +(ComplexNumber left, ComplexNumber right)
    {
        return new ComplexNumber(left.realPart + right.realPart,
            left.imaginaryPart + right.imaginaryPart);
    }

    public static implicit operator ComplexNumber(double d)
    {
        return new ComplexNumber(d, 0);
    }

    public static explicit operator double (ComplexNumber c)
    {
        if (c.imaginaryPart == 0)
            return c.realPart;
        else
            throw new InvalidCastException("Imaginary part is non-zero");
    }
}


public class ComplexNumber
{
    private readonly double realPart;
    private readonly double imaginaryPart;

    public ComplexNumber(double real, double imag)
    {
        this.realPart = real;
        this.imaginaryPart = imag;
    }

    public double Magnitude
        => Math.Sqrt(realPart * realPart + imaginaryPart * imaginaryPart);

    public override string ToString()
        => string.Format("{0}, {1}", realPart, imaginaryPart);

    public static ComplexNumber operator + (ComplexNumber left, ComplexNumber right)
        => new ComplexNumber(left.realPart + right.realPart,
            left.imaginaryPart + right.imaginaryPart);

    public static implicit operator ComplexNumber(double d) => new ComplexNumber(d, 0);

    public static explicit operator double (ComplexNumber c)
    {
        if (c.imaginaryPart == 0)
            return c.realPart;
        else
            throw new InvalidCastException("Imaginary part is non-zero");

}

Compare for yourself which of these two versions is more readable. Which would you prefer to read and maintain? Even in the new version, notice that one of the methods uses the classic syntax. The test to make sure that the imaginary part is 0, combined with throwing the exception, makes the classic member syntax cleaner.

Expression bodied members will become part of your daily coding habits as soon as your team adopts C# 6. You'll type less and write more maintainable and understandable code. This series will help prepare you for the new features in C# 6, so you'll be more productive and create better programs.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020