private readonly float[] _location;
public Player()
{
_location = new float[3];
}
public float[] Location
{
get
{
_location[0] = Worker.Elements["lbXCoordinate"].Value;
_location[1]= Worker.Elements["lbYCoordinate"].Value;
_location[2] = Worker.Elements["lbZCoordinate"].Value;
return _location;
}
}
Two questions:
I often find myself setting the value of a Property in the get Accessor (as seen above), as opposed to using a set Accessor. This way I ensure that whenever someone asks for the value, they get an updated version. Is that generally OK to do?
I realize that returning an Array in a Property is not good practice (link), but I am concerned that if I return a ReadOnlyCollection, then I have to make a new instance of both that and a float every time someone asks for an updated value (see below). It will be asked for several times per second in my program, so that seems to be unwise with regards to performance. Is it okay to just ignore this rule in my case, as the value is actually set every time a user asks for it (so we won't have an issue in the case someone happens to overwrite the array)?
Using ReadOnlyCollection:
private ReadOnlyCollection<float> _location;
public Player()
{
}
public ReadOnlyCollection<float> Location
{
get
{
_location = new ReadOnlyCollection<float>(new float[] {Worker.Elements["lbXCoordinate"].Value, Worker.Elements["lbXCoordinate"].Value, Worker.Elements["lbXCoordinate"].Value});
return _location;
}
}