Expression-bodied properties vs. {get; set;}

Max picture Max · May 18, 2017 · Viewed 18.7k times · Source

When I have Visual Studio 2017 generate properties for me, it will always use the new expression-bodied properties, for example:

private static string username;
internal static string Username { get => username; set => username = value; }

Is there any advantage of using this style over the following or is it just a matter of preference and readability?

internal static string Username { get; set; }

Answer

Sergey picture Sergey · May 18, 2017

Expression-bodied syntax is convenient to use it in the following cases:

Get or Set only property

public DateTime Date => DateTime.Now;

Methods

public IEnumerable<string> GetData => SomeMethodThatReturnData.Select(x => x.Name);

And constructor with 1 input parameter

public SomeClass(IRepository repository) => _repository = repository;