C
C#14mo ago
Carl

✅ 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
Kiel
Kiel14mo ago
you're talking about the difference between
public int SomeValue;
public int SomeValue;
and
public int SomeValue { get; set; }
public int SomeValue { get; set; }
? 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:
private int _someValue;

public int SomeValue
{
get => _someValue;
set
{
if (value == 42)
throw new MeaningOfLifeException();

_someValue = value;
}
}
private int _someValue;

public int SomeValue
{
get => _someValue;
set
{
if (value == 42)
throw new MeaningOfLifeException();

_someValue = value;
}
}
Another usecase for properties is limiting other classes' ability to read/write to the property as needed.
public int SomeValue { get; private set; }
public int SomeValue { get; private set; }
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 class
Carl
CarlOP14mo ago
Yes, that's my question about. Thank you for your answer, you have 2 more examples that I can see how better it is
Want results from more Discord servers?
Add your server