Fields and properties Best Practice in C#
c#, c#-3.0
Solution
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!
Problem
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 ...