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?
Properties can be marked as public , private , protected , internal , protected internal , or private protected . These access modifiers define how users of the class can access the property.
You can initialize a ReadOnly property in the constructor or during object construction, but not after the object is constructed.
The readonly keyword is a modifier that can be used in four contexts: In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class.
The get method returns the value of the variable name . The set method assigns a value to the name variable. The value keyword represents the value we assign to the property.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With