Static constructor and inheritance

I read Jeffrey Richter - CLR through C # and decided to make some test applications. I need help to understand what exactly is happening and why. And yes, I know, public ownership is a bad idea, but my question is not about code style. So:

class ClassA
{
    public static int val1;

    static ClassA
    {
        val1 = 10;
    }
}

class ClassB : ClassA
{
    public static int val2;

    static ClassB
    {
        val1 = 15;
    }
}

And now we call the console output in the following order:

Console.WriteLine(ClassB.val1);
Console.WriteLine(ClassB.val2);
Console.WriteLine(ClassB.val1);

Output:

10
0
15

So, as I understand it, the compiler will make the call static ctorwhen the static member of this type is used for the first time. Right before use. So why static ctor ClassBdoesn't it call on the first line? Is this all because static members are not inherited, so just name the base type in the first line? Explain plz. Thank.

+4
2

Console.WriteLine(ClassA.val1);, , , . ClassB.val1 - . val1 ClassA ClassB .

+7

@Euphoric . IL ( LinqPAD)

IL_0001:  ldsfld      UserQuery+ClassA.val1
IL_0006:  call        System.Console.WriteLine
IL_000B:  nop         
IL_000C:  ldsfld      UserQuery+ClassB.val2
IL_0011:  call        System.Console.WriteLine
IL_0016:  nop         
IL_0017:  ldsfld      UserQuery+ClassA.val1
IL_001C:  call        System.Console.WriteLine

ClassA..ctor:
IL_0000:  ldarg.0     
IL_0001:  call        System.Object..ctor
IL_0006:  ret         

ClassB..ctor:
IL_0000:  ldarg.0     
IL_0001:  call        UserQuery+ClassA..ctor
IL_0006:  ret         

http://share.linqpad.net/a5gjhv.linq

+3

Source: https://habr.com/ru/post/1539792/


All Articles