Skip to content

Instantly share code, notes, and snippets.

@greendimka
Last active April 13, 2018 01:01
Show Gist options
  • Save greendimka/3d36f80b00300806d136905629e5c53c to your computer and use it in GitHub Desktop.
Save greendimka/3d36f80b00300806d136905629e5c53c to your computer and use it in GitHub Desktop.
For a blog "Calculated properties – three strategies"
public class Square {
private int _SideLength;
public int SideLength {
get => _SideLength;
set => _SideLength = value;
}
public int Area {
get => _SideLength * _SideLength;
}
}
public int Area {
get => _SideLength * _SideLength;
}
public class Square {
private int _SideLength;
private int _Area;
/* a constructor */
public Square() {
UpdateArea();
}
public int SideLength {
get => _SideLength;
set {
// we update related property
_SideLength = value;
// after that we recalculate _Area
UpdateArea();
}
}
private void UpdateArea() {
_Area = _SideLength * _SideLength;
}
public int Area {
get => _Area;
}
}
public class Square {
private int _SideLength;
private int _Area;
// our internal indicator
private bool _dirtyArea = true;
public int SideLength {
get => _SideLength;
set {
_SideLength = value;
// here we set it to true,
// _Area must be recalculated
_dirtyArea = true;
}
}
private void UpdateArea() {
_Area = _SideLength * _SideLength;
// here we set it to false,
// _Area is ok to use now
_dirtyArea = false;
}
public int Area {
get {
// check our “dirty” indicator
if (_dirtyArea) UpdateArea;
return _Area;
}
}
}
public Square(bool calculate) {
if (calculate) UpdateArea();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment