#1,217 – C# 6.0 – Using Lambda Expressions for Function Members

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

            Func<int,int> doubleMyNumber = (i) => 2 * i;

In C# 6.0, you can also use a lambda expression as the body of a function member. 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;

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

5 Responses to #1,217 – C# 6.0 – Using Lambda Expressions for Function Members

  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?

    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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: