I have the following classes:
class X
{
int x = 100;
}
class Y:X
{
int y = 100;
}
and the following decompiled code:
class X
{
int32 x;
public void X()
{
this.x = 100;
base.Object();
}
}
class Y:X
{
int32 y;
public void Y()
{
this.y = 100;
base.X();
}
}
so when I create an instance of Y
as in new Y();
I thought that first is created an instance of X
type and then an instance of type Y
because X
is the base class and that base class must be created first than its derived class (Y
).
However reading the decompiled code this
exists before base
and how is possible if base
should be created before than this
?
Maybe does it exist only one object? And we must always call, first, base class constructor only for initializing purpose?
Practically which is the raison to call first base class constructor if we cannot must create first an instance of that type?
Very confused!
Maybe does it exist only one object?
Yes, exactly. A single object is created, which immediately is of the type specified (Y
in this case). All fields (across the inheritance hierarchy) are initially set to the default values of their corresponding types. A single object is created, and then initialized using constructors. Starting from the most derived class, the specified constructor is executed:
this(...)
, that is executed. Otherwise, field initializers are executed.base()
There's no idea of "base
being created" or "this
being created".
This is described in sections 7.6.10.1 and 10.11 of the C# 5 specification.
See more on this question at Stackoverflow