I have following code, which is confusing me a lot. The thing is that when static field abc will be initialized by CLR, it will be kinda instantiation of class ABC which will further instantiate class XYZ. My confusion is that in a multi-threaded environment before the threads do anything with the class Program and it's members, CLR would have already initialized field abc which means any threads trying to run DoSomething() method will have to share abc field (which is also an instance of ABC). Does this mean that class XYZ will only be instantiated once since when CLR initialized abc field just once and it's a shared field.
public class XYZ
{
public XYZ(string nameOfClass)
{
Console.WriteLine("XYZ ctor ran");
}
}
public class ABC
{
private XYZ xyz = null;
public ABC(string nameOfClass)
{
xyz = new XYZ(nameOfClass);
}
public void DoSomething()
{
Console.WriteLine("DoSomething Ran");
}
}
public class SomeClass
{
static ABC abc = new ABC("Program");
public void Helper()
{
abc.DoSomething();
}
}
public class Program
{
static void Main()
{
SomeClass sc = new SomeClass();
SomeClass sc2 = new SomeClass();
for (int i = 0; i < 20; i++)
{
new Thread(sc.Helper).Start();
}
sc2.Helper();
}
}