#642 – Reassigning the this Pointer in a struct

The this keyword in a struct refers to the current instance of the object represented by the struct.  

You can actually assign a new value to the this keyword, provided that the new value is an instance of the same struct.

    public struct BoxSize
    {
        public double x;
        public double y;
        public double z;

        public BoxSize(double x, double y, double z)
        {
            this.x = x;
            this.y = y;
            this.z = z;
        }

        public void CopyFrom(BoxSize newBoxSize)
        {
            // Overwrite existing BoxSize with a new one
            //   by assigning new value to this keyword
            this = newBoxSize;
        }

        public void PrintBoxSize()
        {
            Console.WriteLine(string.Format("X={0}, Y={1}, Z={2}", x, y, z));
        }
    }
        static void Main()
        {
            BoxSize myBox = new BoxSize(5, 2, 3);
            myBox.PrintBoxSize();

            myBox.CopyFrom(new BoxSize(10, 20, 30));
            myBox.PrintBoxSize();
        }

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: