Question

I read Jeffrey Richter - CLR via C# and decide to make some test applications. I need some help to understand what exactly happen and why. And yes i know, public property is bad idea, but my question 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 output to console in this order:

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

Output is:

10
0
15

So, as i understand, compiler will make call of static ctor when static member of that type used for first time. Right before usage. So why it call static ctor of ClassB not at the first line? It's all because static members not inherit, so it just call base type in first line? Explain plz. Thanks.

Was it helpful?

Solution

Because the first call will be converted internally to Console.WriteLine(ClassA.val1); which is how the call should look like in the first place. Being able to call ClassB.val1 is just convenience from compiler's side. The val1 field is only related to ClassA and unrelated to ClassB from runtime's side.

OTHER TIPS

To add to @Euphoric answer. This is IL generated (displayed by 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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top