Showing posts with label Consumed. Show all posts
Showing posts with label Consumed. Show all posts

Constructor Sequence

Friday, May 27, 2011

This sample code will ease your understanding about constructor that when constructor is called.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConstructorSequence
{
    class One
    {
        public One()
        {
            Console.WriteLine("Constructor of class One");
        }


        static void Main(string[] args)
        {
            Console.WriteLine("Begin Main Method");
            Two t = new Two();
            Console.WriteLine("End Main Method");
            Console.Read();
        }
    }


    class Two : One
    {
        public Two()
        {
            Console.WriteLine("Constructor of class Two");
        }
    }
}

Output will be:


As you can observed that:
  1. First, Main() method will be run and according to first line of this method, result will be "Begin Main Method".
  2. Second line of Main() method will going to create object of Class Two by the statement "Two t = new Two();".
  3. Remember, whenever new object has going to create the following three things will be done:
    1. Constructor of the class for which an object creation is requested will called.
    2. Memory space will be consumed to store that object.
    3. Return the reference of that object to do any thing in future with this object.
  4. As per above knowledge base, the constructor of class Two will be called and again Remember one thing that before going into the body of called constructor while creating object there is one thing which is implicitly defined i.e. "Calling of Base/Parent Class constructor". This is called containment.
  5. So, before going to the line "Console.WriteLine("Constructor of class Two");" constructor of Class One will be called and which resulted "Constructor of class One".
  6. After this, actual code of Class Two's constructor will be run and resulted "Constructor of class Two".
  7. Now above mentioned three steps for creating object has been performed and its time to leave the line "Two t = new Two();". So, next printed line will be "End Main Method".
If you have any question regarding this flow contact me i will try my level best to help you.

**************************LINKS******************************

I have created a new better blog:

My Youtube channel:

**************************LINKS******************************