✅ About get; set properties
Hi, I have a question about get/set properties.
Is that using get; set; properties always better without using them? Is there any affect if I use all my properties with them?
2 Replies
you're talking about the difference between
and
?
From my experience, the second is always preferred nowadays.
public
fields have a lot less control over accessibility and visibility, specifically when it comes to setting and getting the value. properties (the second example) are the more modern and recommended way to do things, EVEN IF you are just doing get; set;
for everything.
properties in general are just much more flexible. You can do cool things like have a property with a backing field that you can do (simple) data validation on as the property is set, for example:
Another usecase for properties is limiting other classes' ability to read/write to the property as needed.
Any other class can read SomeValue, but only the class it's in can modify its value.
IMO, it's better to just use properties everywhere* for consistency.
*fields are still OK for private variables you need shared within a classYes, that's my question about. Thank you for your answer, you have 2 more examples that I can see how better it is