Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding three static fields

Tags:

c#

static

field

In the below code if we use constant fields, Result will be OK! but when we use static field, the result isn't expected.

Why and How?

class Program
{
    private static int x = y + 100;
    private static int y = z - 10;
    private static int z = 300;

    public static void Main(string[] args)
    {
        System.Console.WriteLine("{0}/{1}/{2}",x,y,z); // 100/-10/300  why and how?
        Console.ReadKey();
    }
}
like image 302
Ayub Avatar asked May 07 '26 20:05

Ayub


1 Answers

Member variables are initialized in the order they appear in the file. At the time x is initialized, y and z are both 0.

like image 117
Dave Mackersie Avatar answered May 09 '26 08:05

Dave Mackersie