5
athlon
7y

Can someone explain me if and when should I use get and set in C#? And what are the advantages compared to for instance "value = 1"?

Comments
  • 4
    When you need to change the value of a private property in a class.
    Without the "set" declaration the value is read-only and you can't modify it.

    It reduces the risk of errors, and make the input check more clear.
  • 1
    @JS96 So for instance, I wanna give player money and the value is in Statistics class. So I should make private int _money;, add public int Money { get => _money; set => value; }? Or just simple Statistics.money += value; would do?
  • 1
    It's not about only changing the value of a private property. You can add additional logic and error checking when setting a value.
Add Comment