about struct (e.g. System.Drawing.Point)

  • Thread starter Thread starter Action
  • Start date Start date
A

Action

Point is a struct
but I can do both

Point a;
Write(a.X);
Write(a.Y);

and
Point a = new Point(1,1);
Write(a.X);
Write(a.Y);
.....seems confusing!
 
Action said:
Point is a struct
but I can do both

Point a;
Write(a.X);
Write(a.Y);

Yes, although it's a bad idea to do that - I'd always write the above
as

Point a = new Point();
Write (a.X);
Write (a.Y);

It'll do the same thing (always, I believe) but it means that the whole
of the struct is definitely assigned.
and
Point a = new Point(1,1);
Write(a.X);
Write(a.Y);
....seems confusing!

Why? Basically "new" returns a new *value* for value-types, not a new
reference.
 
Does this mean that
Point a = new Point(1,2);
Write (a.X);
Write (a.Y);
1. a new Point is created
2. Value of the newly created Point is assigned to Point "a"
3. the "new Point" is destroyed, as Point "a" is a struct, it didn't really
points to the "new Point", so the "new Point" has zero reference => GC clean
it up....

is this the case?
thx!
 
Action said:
Does this mean that
Point a = new Point(1,2);
Write (a.X);
Write (a.Y);
1. a new Point is created
2. Value of the newly created Point is assigned to Point "a"
3. the "new Point" is destroyed, as Point "a" is a struct, it didn't really
points to the "new Point", so the "new Point" has zero reference => GC clean
it up....

is this the case?

Not quite - because Point is a value type, there *is* nothing on the
heap to be cleaned up. It's just the same as doing:

int a=5;
int b=10;
int x = a+b;

- the addition is performed, and the value is assigned to x. Exactly
the same kind of thing is happening here - the point is created, and
then assigned to the variable. At no point does anything need to be on
the heap - there are no references involved.
 
Back
Top