#694 – Sequence of Events for Chained Constructors

When you chain constructors together using the this keyword, one constructor calls another while an object is being created.

When one constructor chains to another, the constructor being chained to is executed first, followed by the body of the original constructor.

For example, assume that we have three Dog constructors, as shown below.

        public Dog(string name, int age, string favToy)
        {
            Console.WriteLine("name/age/favToy constructor executing");
        }

        public Dog(string name, int age)
            : this(name, age, "ball")
        {
            Console.WriteLine("name/age constructor executing");
        }

        public Dog(string name)
            : this(name, 1)
        {
            Console.WriteLine("name constructor executing");
        }

If we create a Dog object and pass it only a single argument, of type string, the code in the body of each constructor will be executed in the following order:

  • name/age/favToy constructor
  • name/age constructor
  • name constructor

 

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.

One Response to #694 – Sequence of Events for Chained Constructors

  1. Thanks! I think I will keep coming back to reference this forever because I can never remember the sequence….

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: