Re: Boxing & UnBoxing access question
From: Bruce Wood (brucewood_at_canada.com)
Date: 03/03/05
- Next message: Bruce Wood: "Re: Boxing & UnBoxing access question"
- Previous message: Bob Powell [MVP]: "Re: Preload an image?"
- In reply to: Ajay Kalra: "Re: Boxing & UnBoxing access question"
- Next in thread: Bruce Wood: "Re: Boxing & UnBoxing access question"
- Reply: Bruce Wood: "Re: Boxing & UnBoxing access question"
- Messages sorted by: [ date ] [ thread ]
Date: 3 Mar 2005 10:19:21 -0800
But a Point isn't an object... that's the... um... point. :)
I suppose it does boil down to a personal style thing. I prefer to keep
it clear in my head that value types such as Points aren't objects, and
manipulating them as if they were, while it often works, requires that
you keep a more sophisticated mental model of what's going on.
In the particular example I gave:
public void UpdatePoint(ref Point p)
{
p.X = 5;
}
versus
public void UpdatePoint(ref Point p)
{
p = new Point(5, p.Y);
}
It is true that one more Point value is being created (the temporary
one created by new Point(), before it's assigned to p), but this isn't
a heap object being allocated: it's a value that at worst lives briefly
on the stack, and at best is in some register. This is _not_ like
saying "new DataTable()" and then cloning it. Value types are much more
lightweight in terms of resources.
Look at these two examples:
public Point UpdatePoint(Point p)
{
p.X = 5;
return p;
}
versus
public Point UpdatePoint(Point p)
{
return new Point(5, p.Y);
}
Here there is _no difference_ whatsoever. Well, at least the compiler
could easily optimize away any difference. A new Point needs to be
copied onto the stack in any event as a return value. Whether you
modify p and then copy that into the return area, or build a new Point
directly into the return area using p as a model... it's all the same.
In the end, I suppose that it doesn't matter, except that saying
p.X = 5;
lulls my feeble brain into forgetting that I'm dealing with a value
type, which in turn gets me into the kinds of trouble that Ed
experienced. I prefer to clearly separate value types and reference
types by convention: I always change value types by making new ones and
assigning them. I just helps me keep things straight in my head. :)
- Next message: Bruce Wood: "Re: Boxing & UnBoxing access question"
- Previous message: Bob Powell [MVP]: "Re: Preload an image?"
- In reply to: Ajay Kalra: "Re: Boxing & UnBoxing access question"
- Next in thread: Bruce Wood: "Re: Boxing & UnBoxing access question"
- Reply: Bruce Wood: "Re: Boxing & UnBoxing access question"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|