5

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.

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.