With C#6 came some new features, including getter-only auto-properties and property-like function members.
I'm wondering what are the differences between these two properties? Is there any reason why I'd prefer one to another?
public class Foo
{
public string Bar {get;} = "Bar";
public string Bar2 => "Bar2";
}
I know that {get;} =
can only be set by a static
call or a constant value and that =>
can use instance members. But in my particular case, which one should I prefer and why?
It's easiest to show them in terms of C# 1:
public class Foo
{
private readonly string bar = "Bar";
public string Bar { get { return bar; } }
public string Bar2 { get { return "Bar2"; } }
}
As you can see, the first involves a field, the second doesn't. So you'd typically use the first with something where each object could have a different state, e.g. set in the constructor, but the second with something which is constant across all objects of this type, so doesn't need any per-object state (or where you're just delegating to other members, of course).
Basically, ask yourself which of the above pieces of code you would be writing if you didn't have C# 6 available, and choose the corresponding C# 6 path.
See more on this question at Stackoverflow