#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.CopyFrom(new BoxSize(10, 20, 30));


About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: