#642 – Reassigning the this Pointer in a struct
August 6, 2012 Leave a comment
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(); }