James Montemagno
James Montemagno

Live, Love, Bike, and Code.

Live, Love, Bike, and Code



My Favorite C# 7 Feature: More expression-bodied members

I can’t help myself, I love Expression-Bodied Members from C# 6! Combined with other powerful C# features it took this code:

public void OnPropertyChanged(string name)
  var changed = PropertyChanged;
  if(changed == null)
  changed(this, new PropertyChangedEventArgs(name));

to this:

public void OnPropertyChanged(string name)=>
  PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));

This is amazing! However, in C# 7 things get even better. Take our good old friend property setters and getters:

public string Subtitle
  get { return subtitle; }
  set { SetProperty(ref subtitle, value); }

Look at all of those { and }, well no more! Here is some C# 7 for you:

public string Subtitle
    get => subtitle;
    set => SetProperty(ref subtitle, value);

You can even use our lambda friend on constructors and finalizers!!

// Expression-bodied constructor
public ExpressionMembersExample(string label) => this.Label = label;

// Expression-bodied finalizer
~ExpressionMembersExample() => Console.Error.WriteLine("Finalized!");

Mind Blown!! It is the small things that make me so happy. There are tons more great C# 7 features that you can now access in VS 2017 and VS for Mac and Frank and I discuss all of them on our podcast Merge Conflict that I hope you subscribe to!

Merge Conflict 47: You Got Some F# in My C#

Copyright © James Montemagno 2017 All rights reserved. Privacy Policy

View Comments