Hi @Shervan360 ,
In C#, fields are initialized in the order they appear in the class. Therefore, when the compiler encounters public static int X = Y;
, the field Y
has not been initialized yet, but it does exist with its default value, which is 0
for an int
. This is why the value 0
is assigned to X
and no compiler error occurs.
The initialization process works as follows:
- When
X
is being initialized, the fieldY
has been declared but not yet assigned the value3
. It holds the default value for its type, which is0
in this case. - Therefore,
X
gets the value ofY
, which is0
. - Then
Y
gets initialized with the value3
.
Best Regards.
Jiachen Li
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.