-4

No this has not been answered, stop being so fast on the down voting and read, this is why NOT to have a setter accompanying a getter. What you guys have sent so far is how a getter and setter work hand in hand and not why one would have them individually.

What is the point of only having a getter that is not accompanied by a setter? As far as I understand it, we use the getter to get the value and a setter to validate the value inserted.

But I have this code here that leaves me confused.

private int Area { get { return _width * _height } }

What's the point? Nothing is being validated. Why not just make a field holding the value, such as:

private int area = _width * _height

Confusing to say the least.

Bi-HanNoobSaibot
  • 215
  • 1
  • 3
  • 8
  • Look here: https://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property – Miq May 04 '19 at 09:57
  • 4
    In simple terminology, That variable wouldn't be updated.. Where as the getter would be recalculated upon being called. – Adrian May 04 '19 at 09:57
  • -Adriani6, good point. That has to be why, thanks man. – Bi-HanNoobSaibot May 04 '19 at 09:58
  • 3
    Additionally, having an extra field takes more memory per instance, just for redundant information. (Sometimes that's appropriate, if the redundant information is expensive to compute, but definitely not always.) – Jon Skeet May 04 '19 at 10:03
  • Both getter and setter can serve __various__ purposes in addition to getting and setting. Validation is one, setting dependent fields another.. Having no setter can make the variable readonly. – TaW May 04 '19 at 10:35

1 Answers1

0

There are many advantages of writing this instead of a field:

private int Area { get { return _width * _height; } }
  • Area does not have to be manually updated every time _width or _height changes. You might forget to update it in some places.
  • Area won't be accidentally assigned another (incorrect) value. If you try to set this, the compiler will stop you.
  • Having an extra field requires more memory to be allocated as long as the instances are alive. Having a getter like this only costs a little time computing the product of two numbers when you access the property. Since this is only a multiplication, the time it takes here is really, really little.

More generally, you might see some types whose properties are all get-only, such as DateTime. This is done so that the type is immutable, and immutability is good. See Why do we need immutable class?.

Sweeper
  • 213,210
  • 22
  • 193
  • 313