#1,217 – C# 6.0 – Using Expression-Bodied Methods

In C# 5.0, you could use a lambda expression wherever a delegate instance was expected.  For example:

            Func doubleMyNumber = (i) => 2 * i;

In C# 6.0, you use something similar for the body of a function member, known as an “expression-body definition” to define the method. This simplifies the syntax for simple methods.  For example:

    public class Dog
    {
        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
        }

        public string Name { get; protected set; }
        public int Age { get; set; }

        public void AgeIncrement() => Age++;
        public int AgeInDogYears() => Age * 7;
    }
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

5 Responses to #1,217 – C# 6.0 – Using Expression-Bodied Methods

  1. Pingback: Dew Drop – November 3, 2014 (#1890) | Morning Dew

  2. illidans4 says:

    Technically, it isn’t a lambda expression.

  3. Mark Pearce says:

    While this is using lambda syntax, it isn’t a lambda expression and the compiler isn’t converting anything to delegates. BTW, great work on this C# and the WPF series – very useful.

  4. Loadmaster says:

    Does the syntax allow you to enclose the lambda expression within parentheses, for better readability?

    Example:
    Func doubleMyNumber = ((i) => 2 * i); // Parens added

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: