Still here

October 23, 2007 19:57 by dgood
I am America (And So Can You!) - One word:  Hilarious.  Technically, that's three.

Yes, I'm still alive.  I've been very busy lately.  I jacked up the radiator cap on my Jeep and I've been busy putting a new Jeep under it.

ProgrammingGoody, you say?  Blog about software, eh?

How's this:  Boxing and Unboxing in C# can be tricky operations for the inexperienced or uninformed.

Example:

struct Point
{
    int X;
    int Y;
    public Point(int x, int y){ X=x; Y=y; }
    public void Move(int x, int y){ X = x; Y=y; }
}

public static void main(string args[])
{
    Point p = new Point(0, 0);                // value type
    ArrayList arr = new ArrayList();      // only holds reference types
    arr.Add(p);                                         // Box it

   ((Point)arr[0]).Move(5, 5);               // Unbox it

   Console.WriteLine("Point: {0}", arr[0]);
}

When the Point struct is unboxed, the pointer to the boxed Point on the managed heap is used to copy the values from the heap into a new instance of a Point value type on the stack.  In effect, there are now two separate instances of Point - one on the stack and one on the heap.  Using Point in this manner will not lead to the desired outcome.

The same mechanism applies to any value type stored as a boxed reference.  (Hint: think Session state)


This one's for you, Classic Colin.

Cheers.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

Comments are closed