Reputation: 6330
I am not clear about why the SecondChild
class DoSomething
is not getting called again when Child
class is getting initialized.
class Parent
{
public Parent()
{
DoSomething();
}
protected virtual void DoSomething()
{
Console.WriteLine("Parent Method");
}
}
class Child : Parent
{
private string foo;
public Child()
{
foo = "HELLO";
}
protected override void DoSomething()
{
Console.WriteLine(foo.ToLower());
}
}
class SecondChild : Parent
{
public SecondChild()
{
var c = new Child();
}
protected override void DoSomething()
{
Console.WriteLine("In second Child");
}
}
class Program
{
static void Main(string[] args)
{
SecondChild c = new SecondChild();
Console.ReadLine();
}
}
I was expecting that DoSomething()
of SecondChild
will be called twice here, but instead Child
class DoSomething()
is invoked which will give NullException.
Upvotes: 4
Views: 814
Reputation: 1331
Well DoSomething() its get called when create an instance of SecondChild class, but when you create and instance of class Child, first it execute the constructor of Parent class, which is calling DoSomething method of the child class which is OK, but because the constructor of Child class is not executed yet, foo field is not yet and doing foo.ToLower() throws null reference exception.
DoSomething is getting called twice once of Child class and once for SecondChild, but for Child class is throwing exception because of foo is null
So the tricky part here the base constructor get executed before the constructor of the derived class
Upvotes: 0
Reputation: 4381
I have adjusted Your definition a bit:
class Parent
{
protected string foo;
public Parent()
{
foo = "Parent1";
DoSomething();
foo = "Parent2";
}
protected virtual void DoSomething()
{
Console.WriteLine("Parent Method");
}
}
class Child : Parent
{
public Child()
{
foo = "HELLO";
}
protected override void DoSomething()
{
Console.WriteLine(foo.ToLower());
}
}
class SecondChild : Parent
{
public SecondChild()
{
var c = new Child();
}
protected override void DoSomething()
{
Console.WriteLine("In second Child");
}
}
class Program
{
static void Main(string[] args)
{
SecondChild c = new SecondChild();
Console.ReadLine();
}
}
Output for this will be:
In second Child
parent1
Reason why? Look at the method call order:
new SecondChild()
-> SecondChild:base()
-> base.DoSomething() //virtual
-> SecondChild.DoSomething()
-> new Child()
-> Child:base()
-> base.DoSomething() //virtual
-> Child.DoSomething()
Upvotes: 4