Dear all, which one is the best practice using C# and why?
1.
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
2.
public string Name { get; set; }
3.
protected string name;
public string Name
{
get { return name; }
set { name = value; }
}
4. Please add ...
Snippets 1 and 2 are both fine. The second is simply a more convenient way of writing the first for when you don't need access to the underlying field.
Snippet 3, however, should generally be avoided (unless you have some specific reason for needing it), as fields should almost always be private. If you need to provide a different way of setting the field for descendant classes (which is unlikely), then you could use methods or another property.
Remember that a protected member is essentially just a slightly more restricted public member, since it can be accessed by client code as long as it's in a descendant class. This means that client code can become tied directly into the implementation of the class rather than its interface, which is a bad thing!
Start with the second snippet, i.e.
public string Name { get; set; }
Change it to the form of the first snippet when you need to add validation, or do some logic when the value is set.
I'd avoid the last option, as it would allow an overriding class to directly access the backing field which ties you to a specific implementation (it also means that your lovely validation can be bypassed)
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