Beware! expression bodied properties will execute the expression every time they are called! You can see the examples in the last part of my answer.
public string Name => "bob";
Is syntactic sugar for
public string Name
{
get
{
return "bob";
}
}
While
public string Name { get; } = "bob";
is syntactic sugar for
private readonly string _name = "bob";
public string Name
{
get
{
return _name ;
}
}
Check it out yourself.
Beware - here is the dangerous part!
Please note that the expression body will be executed every time you call this property. That's fine when it's returning a hard coded value, but if it's returning a list, for example, it will return a new list every time:
public List<String> Names => new List<String>() {"bob"};
Is syntactic sugar for:
public List<string> Names
{
get
{
return new List<string>() {"bob"};
}
}
That is not the case with auto-property initialization:
public List<String> Names { get; } = new List<String>() {"bob"};
Is syntactic sugar for this:
private readonly List<string> _names = new List<string>() {"bob"};
public string Names
{
get
{
return _names;
}
}
As you can see, here the list is only initialized once.
Check it out yourself.