This code seems to not call the Mixed
constructor and prints y = 0
public class Mixed
{
public int x;
public static int y;
public Mixed()
{
x = 1;
y = 1;
}
}
public class Program
{
static Mixed mixed = new Mixed();
static void Main(string[] args)
{
Console.WriteLine("y = " + Mixed.y);
Console.ReadLine();
}
}
However, simply modifying the Main
function to look like this results in the constructor being called.
static void Main(string[] args)
{
Console.WriteLine("x = " + mixed.x);
Console.WriteLine("y = " + Mixed.y);
Console.ReadLine();
}
This prints:
x = 1
y = 1
Why does simply adding this reference to a non-static field result in the constructor being called correctly? Shouldn't creating the object always result in a constructor being called, regardless of how that object is used later in the program?
Oddly enough, making the Mixed
object non-static like this also results in the constructor being called:
public class Program
{
static void Main(string[] args)
{
Mixed mixed = new Mixed();
Console.WriteLine("y = " + Mixed.y);
Console.ReadLine();
}
}
However, this doesn't seem to make sense to me either. Declaring the Mixed
object as static should only imply that there is only one copy of the object in memory, regardless of how many times Program is instantiated. Is this some sort of compiler optimization that for static fields the compiler waits for a reference to a non-static field of that type before actually instantiating it?