Why the order of entering static .ctors is different from instance .ctors in inherited classes?
-
22-04-2021 - |
Question
Why var b = new B()
firstly enters static B()
.ctor and than static A()
.ctor
and not vice versa like the instance constructors does (public A()
and than public B()
)?
public class A
{
static A() {}
public A() {}
}
public class B : A
{
static B() {}
public B() {}
}
La solution
Technically the instance constructor of B
is entered first. But the first thing it does is calling the constructor of A
and only then goes to the user defined body.
So I assume that directly before the constructor of B
is entered the static constructor of B
needs to run.
Then the constructor of B
calls the constructor of A
, which triggers the static constructor of A
.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow