简体   繁体   中英

Derived Class instantiates 2 objects of BASE Class

I have a basic query. I have a derived class which is empty. I notice that when I run the below pasted piece of code (runs in Linqpad), I end up with 4 objects of the BASE Class. My understanding is when we instantiate a derived class object, in absence of its own constructor, BASE Class constructor would be invoked, resulting in 1 instance of the derived class.

void Main()
{

  NestedS n1 = new NestedS();   
  NestedS n2 = new NestedS();    
  NestedS n3 = new NestedS(); 


}

public class Base1
{

private static readonly Base1 instance = new Base1();
private static int numInstance = 0;
private readonly object lock1 = new object();

public Base1()
{

 lock(lock1) 
 {
  numInstance.Dump("before");
  numInstance++;
  numInstance.Dump("here");
  }
}

}

public  class NestedS : Base1{

}

The code results in 4 instances of the derived class. Can someone explain to me the reason behind the same.

Update: Sorry, rephrasing my query here, pasting output as well. From output, numInstance should have been initialized to 1 already before second instance is created, but it is still 0 at time of second instance creation:

before

0 


here

1 


before

0 


here

1 


before

1 


here

2 


before

2 


here

3 ```

The reason for your surprising output comes the lines

private static readonly Base1 instance = new Base1();
private static int numInstance = 0;

The language standard says about field initializers ( https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes#variable-initializers ) (emphasis mine)

[...] when a class is initialized, all static fields in that class are first initialized to their default values, and then the static field initializers are executed in textual order

So your code first creates instance , which sets numInstances to 1 and afterwards executes the line numInstance = 0; "resetting" the field to 0 .

Changing the order of the declarations to

private static int numInstance = 0;
private static readonly Base1 instance = new Base1();

Produces the result you were expecting, as numInstances gets initialized to 0 (technically twice) first before you construct the first instance. Alternatively you could also just remove the initializer from numInstances as the default value for int is 0 anyway

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM