[Solved] variables that is used before declaration but declared after use [closed]


As much as I can perceive, the thing which is baffling you is the order of code in which it is declared. Have a look at below code:

class Program
{
    public Program()
    {
    }

    public  void myFunc()
    {
        canIAccessIt = 10;
    }

    public  int canIAccessIt = 0;
}

As in above code anyone from C language background (ignore class part which doesn’t exist in C) might get into a thinking that myFunc function is trying to access a variable canIAccessIt even before it has been declared or has come into scope.

Scope of variables in C# .Net world doesn’t work that way. A class level variable (aka member variable) gets associated with the instance of the object instead and comes into scope from the time the object is created till the time object is destroyed or garbage collected.

Like in the above case, one might think that canIAccessIt variable might not have come to life as it is declared below myFunc method. It is not so.

When my above code is compiled by C# compiler it becomes something like this in MSIL (Microsoft intermediate language) written inside your *.dll file which is the output of the C# project building process:

class Program
{
    public  int canIAccessIt;
    public Program()
    {
        canIAccessIt = 0;
    }

    public  void myFunc()
    {
        canIAccessIt = 10;
    }
}

Note: The above MSIL code is just for your reference purpose so that you can understand it. MSIL code looks much more weird than this as it has to be understood by the CLR rather than a user or a programmer.

So for compiler it doesn’t matter where the global variable is declared inside your class. As long as it is inside the opening({) and closing curly brace (}) of your class then its initialization will get moved inside the constructor of your class. Constructor of a class is the first method which gets called whenever you new-up a class instance. The moment it happens your variable will come to life (intantiated and initialized) and become in-scope to be used by myFunc method.

The only difference with i variable in your class is that it is static so its initialization will move the static constructor of your class rather than an instance constructor of your class. Life-time and scope of your i variable is associated with Type instance (aka static instance) of your class.

So whenever you initialize your class for the first time to be able to call your ReplaceCC method here is the sequence of events:

  1. Instance constructor gets called.
  2. Static constructor gets called – It initializes your static i variable.
  3. Then you call ReplaceCC method on the object instance when i is already instantiated and initialized.

You can also look at this answer which seconds my thoughts.

solved variables that is used before declaration but declared after use [closed]