The c# Point structure

Hello,

I am writing an application for the construction industry which contains a graphics module.

In this module points are typically being generated and modified (ie the location of those points).

I have a C++ background and am reasonably knowledgeable on c# theory and I realise the differences between structures and classes regarding the use of the 'new' keyword.

When it is required to generate a new point I use the code :

Point pt1;

pt1 = new Point(a,b);

Now when it is required to move the point I use the code :

pt1.X = c;      //technique 1
pt1.Y = d;

Q. However I am wondering what would be the implications of using the following code to update an existing point  ie :

pt1 = new Point(c,d);   //technique 2

Because Point is a value type I believe that the result would be that the point pt1 would be reside on the system stack (not heap).

(If) I were to keep using technique 2 to alter the points location would the system keep creating additional (different) addresses/locations on the stack for each call to the new keyword  ie
pt1 = new Point(e,f);  
pt1 = new Point(g,h);
.....                 
resulting in numerous structures of pt1    (This is definitely not desired)

OR

Would the system recognise that pt1 refers to the same structure and with each call involving the 'new' keyword, simply modify the one address/location on the system stack  with the new values

Thanks


Andrew.  


Answer this question

The c# Point structure

  • Nianz

    You have raised some good points - thanks

    Andrew

  • Ramzee

    You should do what you're doing ( change the values of the point ).  If you call new, a new one is created, and the old one is disposed of.  This is a waste of time in this case, but I don't believe the compiler would work this out.

  • Docile

    Thanks Christian,

    I understand your comment.

    You mention something upon which I had not given much thought.

    If approach two were used then the previous point would be disposed and that the previous points (pt1) would not accumulate at different locations in the stack ( I was doubtful that they would) 

    Does this mean that the garbage collector acts on the stack (as well as the memory heap)

    Andrew.




  • Ofer Zadikario

    >Because Point is a value type I believe that the result would be that the point pt1 would be reside on the system stack (not heap).

    Not necessarily. It could also be a field in a heap-allocated object.


    >Would the system recognise that pt1 refers to the same structure and with each call involving the 'new' keyword, simply modify the one address/location on the system stack  with the new values

    Yes, sort of. The stack isn't growing, there's no automatic disposing going on and no the GC doesn't "clean up" the stack.



  • The c# Point structure