When I call Main
, the CLR will check all types used in Main
and load these types into the AppDomain.
No, that's not necessarily true. The type loader can load those types earlier if it wishes, or, in some cases, it can delay loading the types.
The mechanism you are assuming is that the jit compiler checks the set of types used by Main
as it jits Main
, and it loads any types that are used but not already loaded, and along the way it initializes static state for those types, right? That's an optimization that the jitter happens to make sometimes. It is not a guarantee of the C# language; C# only guarantees that if you have a static constructor, that it runs before the first instance is created or the first method is executed.
I only reference type A
- will the CLR load type B
?
Yes. All the dependencies of the type A
must be loaded, and that includes the base type.
I think B type will be loaded into AppDomain, but why?
All the dependencies of the type A
must be loaded, and that includes the base type.
The CLR gives how much memory to an instance of type A
?
As much as it needs.
The memory will contain B
's fields?
Yes.
Which ctor will initialize these fields that come from B
? B
's ctor?
The memory allocator will initialize all the fields to their default values; if B's ctor then assigns a different value to the field, that happens when B's ctor runs.
But it is noted that ctor can't be inherited.
Correct. The ctor in B
is not a member of type A
.
how do we call the B
ctor? By the base
keyword?
Correct. If you do not include a base
or this
reference in your ctor, C# will automatically assume that you meant base()
. If there is no matching accessible ctor, then the program is an error, and you must explicitly specify which base constructor you want to call.
how does base
get the B
ctor?
The compiler looks up the metadata token for the appropriate base class ctor and puts it in the implementation of the derived class ctor. You can use ILDASM apparently; use it to look at the A
ctor and you'll see the call to the B
ctor.
I don't have an instance of B
Yes you do. All A
are instances of B
. If you had a class Animal
, and a class Giraffe
that derived from Animal
, and you have an instance of Giraffe
, then you also have an instance of Animal
, right?
Can I use id
from B
?
Obviously yes; you did!