Can we use a field before declaring in C#?

Shervan360 1,601 Reputation points
2024-10-14T10:34:31.6466667+00:00

Hello,

I expect a compiler error because I didn't declare Y before using it.

Can we use a field before declaring in C#?

    class Foo
    {
         public static int X = Y;    // 0 -> I Expect a compiler error here!
         public static int Y = 3;    // 3
    }
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,905 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,996 questions
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 32,056 Reputation points Microsoft Vendor
    2024-10-14T12:05:35.42+00:00

    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:

    1. When X is being initialized, the field Y has been declared but not yet assigned the value 3. It holds the default value for its type, which is 0 in this case.
    2. Therefore, X gets the value of Y, which is 0.
    3. Then Y gets initialized with the value 3.

    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.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.