Reputation: 33
I have the following scenario:
Class A
{
public static A instance;
static A()
{
if(condition)
{
instance = new B();
}
else
{
instance = new A();
}
}
public A()
{
WriteSomething();
}
virtual void WriteSomething()
{
Console.WriteLine("A constructor called");
}
}
Class B : A
{
public B()
{
WriteSomething();
}
override void WriteSomething()
{
Console.WriteLine("B constructor called");
}
}
The problem is that when A.instance is called the first time and if condition is true and the B() constructor is called, for some reasons I do not undestand the output of the program is "A constructor called".
Can you please help with an explanation!
Thank you!
Upvotes: 0
Views: 168
Reputation: 3751
A.WriteSomething() will always give you "A constructor called" B.WriteSomething() will always give you will always give you "A constructor called". However in a constructor scenario, override is not being called, you can use new keyword to make new voids with the same name. This works the way you want besides a virtual override call. However, the code above is not a good implementation.
Class A
{
public static A instance;
static A()
{
if(condition)
{
instance = new B();
}
else
{
instance = new A();
}
}
public A()
{
WriteSomething();
}
public static void WriteSomething()
{
Console.WriteLine("A constructor called");
}
}
Class B : A
{
public B()
{
WriteSomething();
}
public static new void WriteSomething()
{
Console.WriteLine("B constructor called");
}
}
Upvotes: 0
Reputation: 587
The constructor for A
will always run first, even if you are creating a new B
, since B
extends A
.
You have also inadvertently discovered why it's recommended that you don't put virtual function calls in a constructor (at least in .NET).
http://msdn.microsoft.com/en-us/library/ms182331.aspx
"When a virtual method is called, the actual type that executes the method is not selected until run time. When a constructor calls a virtual method, it is possible that the constructor for the instance that invokes the method has not executed."
Upvotes: 1