Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

    Advertisements
  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand
  • Advertisements

Simple invoking order of Constructors

Posted by Paul on December 16, 2010


In this article I am trying to show the order in which constructor and destructors are called for a class and its base class.

Importance

It is of great importance that we should know constructors work in an inherited manner – especially in interviews.

This will give us more clarity in creating or destroying objects in constructors/destructors.

Example

We have a class named ChildClass having a constructor and destructor

Also, a class named ParentClass having a constructor and destructor

image

Whenever the constructor or destructor is called it logs a message to the main form.

Implementation

We create an instance of ChildClass and make Garbage Collector to destroy the instance.

Thus we are able to invoke the entire constructors/destructors involved.

new ChildClass();

Result

We are able to see the result like: Even though we are creating the instance of ChildClass the ParentClass constructor is invoked first.

But while on destruction the ChildClass destructor is invoked first.

image

Class: ParentClass

public class ParentClass

{

    public ParentClass()

    {

        MainForm.AddMessage("ParentClass constructor invoked");

    }

 

    ~ParentClass()

    {

        MainForm.AddMessage("ParentClass destructor invoked");

    }

}

Class: ChildClass

 

public class ChildClass : ParentClass

{

    public ChildClass()

    {

        MainForm.AddMessage("ChildClass constructor invoked");

    }

 

    ~ChildClass()

    {

        MainForm.AddMessage("ChildClass destructor invoked");

    }

}

 

Advertisements

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s