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();
}
}
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.
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.
Output
ReplyDeleteB.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.
B.Static Constructor
ReplyDeleteA.Constructor Hello
B.Constructor
C.Constructor
C.Show()