Constructor in c#


Question: What is the output of the below code? 

namespace ConsoleApplication1
{
    class A
    {
        public A()
        {
            Console.WriteLine("A.Constructor");
        }
        public A(string abc)
        {
            Console.WriteLine("A.Constructor " + abc);
        }
        public void Show()
        {
            Console.WriteLine("A.Show()");
        }
    }
    class B : A
    {
        static B()
        {
            Console.WriteLine("B.Static Constructor");
        }
        public B() : base("Hello")
        {
            Console.WriteLine("B.Constructor");
        }
        public void Show()
        {
            Console.WriteLine("B.Show()");
        }
    }
    class C : B
    {
        public C()
        {
            Console.WriteLine("C.Constructor");
        }
        public void Show()
        {
            Console.WriteLine("C.Show()");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            C obj = new C();
            obj.Show();
            Console.ReadLine();
        }
    }


}



 Sujeet R Singh said...


Output
B.Static Constructor
A.Constructor
B.Constructor
C.Constructor
C.Show()

Explanation: On creation of object of derived class, it executes Parents Constructor. I above scenario it A,B,C
But If any of class contains Static Constructor then it executes first.

Comments

  1. Output
    B.Static Constructor
    A.Constructor
    B.Constructor
    C.Constructor
    C.Show()

    Explanation: On creation of object of derived class, it executes Parents Constructor. I above scenario it A,B,C
    But If any of class contains Static Constructor then it executes first.

    ReplyDelete
  2. B.Static Constructor
    A.Constructor Hello
    B.Constructor
    C.Constructor
    C.Show()

    ReplyDelete

Post a Comment

Popular posts from this blog

iframe vs embed vs object in HTML 5

What is the need of method overriding ???