Advice on struct fields in classes

  • Thread starter Thread starter Marcus Andr?n
  • Start date Start date
M

Marcus Andr?n

Recently I was trying to figure out why a small program I had written
didn't work. It was a simple problem really, normalizing the length of
a couple of coordinates in a vector system and I just couldn't figure
out why the coordinates refused to be changed. Suddenly it hit me what
an idiot I had been as I noticed that the Coordinate structure that I
was trying to change was declared as a property. I was basically
calling the Normalize method on a copy of the class field instead of
on the field itself.

public struct Coordinate{
public void Normalize();
}

public class MyObject
{
private Coordinate coord;
public Coordinate Coord{
get;set;
}
}

MyObject obj = new MyObject()
obj.Coord.Normalize() <--------- Incorrect


After having looked at the different kinds of solutions I decided to
ask this group for opinions on the best way to solve this problem.
First though, I will present what I did come up with during my
brainstorming.

The simplest fix is probably to just expose the Coordinate field
directly and not use property at all. This is however a breach of OO
and could cause problems, for example if I wanted to expose a
Coordinate field in an interface.

A second alternative is to convert it from a struct to a class. This
would of course introduce problems when passing coordinates as
parameters in functions and that makes me vary of this approach.

The last alternative I could think of is to return a new struct value
from the Normalize function that the Property can be set to.

public Coordinate Normalize();
or
public static Coordinate Normalize(Coordinate coord);

The main disadvantage with this alternative is that it is quite a lot
slower than the above versions which could cause a problem if
Normalizing lots of values.

So far I am leaning towards using the static version unless I finds
out that it is a performance bottleneck but I would very much like to
hear other opinions or suggestions.
 
You could provide the methods of the struct directly in class MyObject
and totally hide the instance of the structure, eg:
MyObject myInstance = new MyObject();
myInstance.NormalizeCoords();

function MyObject.NormalizeCoords:
public void NormalizeCoords ( )
{
_coords.Normalize();
}
 
You can either make Coord a class or do the following:

MyObject obj = new MyObject()
Coord c = obj.Coord;
c.Normalize();
obj.Coord = c;
 
Back
Top