#644 – Chaining struct Constructors

In the same way that one constructor for a class can call another, a constructor for a struct can call another constructor, using the this keyword.  In this way, one constructor for the struct calls another, to help initialize the data in the struct.

In the example below, we define two constructors for the BoxSize struct.  The constructor that takes only two parameters chains to the three-parameter constructor, using the this keyword.

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

        // Constructor that fully initializes the object
        public BoxSize(double x, double y, double z)
        {
            this.x = x;
            this.y = y;
            this.z = z;
        }

        // 2nd constructor that allows user to specify
        //   only X & Y and we then default Z to 1.0
        public BoxSize(double x, double y)
            : this(x, y, 1.0)
        {
        }

        public void PrintBoxSize()
        {
            Console.WriteLine(string.Format("X={0}, Y={1}, Z={2}", x, y, z));
        }
    }

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

Leave a comment