C# 7 – Expression Bodied Members

In my C# 6 – First look course, I covered how Expression Bodied Function Members were introduced which permit methods, properties and other function members to have bodies that are expressions instead of statement blocks — similar to lambda expressions.

So we can change this…

private string name = "Jerry Seinfeld";
public string Name
{
    get { return name; }
    set { name = value; }
} 

To this…

public string Name => "Jerry Seinfeld";

In C# 7.0, we now have constructors, accessors, and finalizers (destructors) to the list of things that can have expression bodies:

Constructors
Let’s first look at Constructors…
Before C# 7, we can write a constructor that takes a parameter which looks like this in a class…

        // Classic Constructor
        public Person(string name)
        {
            Name = name;
        }

But now we can convert it to look like this…

// New C# 7 Constructor
public Person(string name) => Name = name;

This is useful if passing in only one or no parameters. Nothing more complicated than that.

Full Properties
The next thing that was changed was for full properties.

        // Classic Full Property
        private string _name;
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

Now can be slightly shortened like this…

        // New C# 7 property
        private string _name;
        public string Name
        {
            get => _name;
            set => _name = value;
        }

Yeah, yeah, you can use auto-implemented properties but for cases you need to write out full properties, this expression body can be done.
Destructors
And lastly, similar to the constructors. Destructors can be shortened.

        // C#6 Destructor
        ~Person()
        {
            Console.WriteLine("Descructor was called!");
        }

Can now be this…

~Person() => Console.Error.WriteLine("C# 7 Destructor was called!");

Definitely pay attention to the evolution of these features and practice them because they are time savers. And without practice, it can make it difficult to understand code by others if you’re not use to it.

My full course on C# 7 First look should be out by April 2017 on Lynda.com. You can check out my C# 6 course first for a refresher since several features in the new version builds on version 6.