CSharp - What is the output: Field Initialization Order

Question

What is the output from the following code

using System;
class A
{
    int x = 10;
    int y = x + 2;
}
class Program
{
    static void Main(string[] args)
    {
        int x = 10;
        int y = x + 2;
        Console.WriteLine("x={0}", x);
        Console.WriteLine("y={0}", y);
    }
}


Click to view the answer

class A
{
        int x = 10;
        int y = x + 2;//Error
}
...
            int x = 10;
            int y = x + 2;//OK
            Console.WriteLine("x={0}", x);
            Console.WriteLine("y={0}", y);

Note

This restriction was implemented by C#.

The statement y=x+2; in the preceding example is equivalent to y=this.x+2;

"this" means the current object.

To make a call like this.x, the current object needs to be initialized first.

But the current object is not initialized at this point.

Related Quiz