#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));
        }
    }
Advertisements

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: