System ProgrammingLearn about Variable Scopes and its Visibility in C# Programming

Learn about Variable Scopes and its Visibility in C# Programming

A variable scope is like the area in which this variable is visible and can be dealt with, assigning to and reading from it. This applies to any code block. When you are inside a function, the variables that you assign there are totally different than the ones that are defined globally, and different than the ones defined in other functions. For example:

static void Main(string[] args)
        {
            string username = "ahmed";
            Console.WriteLine("username is " + username);
            Console.ReadLine();
        }

static void getusername()
        {
            Console.WriteLine(username);
        }

If you try to run the above code, a compile time error will be raised and the code won’t run. This is because although you defined username inside the main function, it cannot be seen in getusername() function as it is not in its scope. The scope of a variable declared inside a function ends by the end of the function code block. Accordingly, if you created another variable with the same name in getiusername() function, it can and will have a different value than the original one. Have a look at the following:

static void Main(string[] args)
        {
            string username = "ahmed";
            Console.WriteLine("username is " + username);
            getusername();
            Console.ReadLine();
        }

        static void getusername()
        {
            string username = "mostafa";
            Console.WriteLine("Local username is " + username);
        }

If you run this code, you will have the following output:

username is ahmed
Local username is Mostafa

The first time it printed the variable, it used the local version defined in the Main() function, while in the second time, it used the local version of the getusername() function. These variables are called local variables.

You can define variables that are shared among functions. These are called global variables. Have a look at the following:

class Program
    {
        static string username;

        static void Main(string[] args)
        {
            string username = "ahmed";
            Program.username = "mostafa";
            Console.WriteLine("username is " + username);
            Console.WriteLine("Global username is " + Program.username);
            Console.ReadLine();
        }
    }

The output of this code should be:

username is ahmed
Global username is Mostafa

Notice here that to refer to the global username, we had to prefix it with the class name, Program. We did this because we have two variables with the same name. However, if the local variable had a different name, we could call the global variable without the need to add the prefix Program.

Variable scope in other blocks

Functions are not the only code structure that have the concept of local variables; any code block does. For example, take a look at the following example that uses an if condition statement:

static void Main(string[] args)
        {
            int i = 0;
            if (i == 0)
            {
                string username = "ahmed";
            }
            Console.WriteLine(username);
            Console.ReadLine();
        }

This code will not run and will raise a compile time error. This is because you created a username string variable inside the if block. The username variable here is local to the containing block only, it cannot be used outside it. The same thing holds for loops.

Learn Cloud Computing from Scratch for Beginners

A closer look at the Main() function

As mentioned in earlier articles, the Main() function is the starting point of your application. It is where the execution starts. When the Main() function exists, the program is terminated. In the previous examples, we used only one form of the Main() function, which is this:

static void Main(string[] args){}

Yet, this is not the only way to call the Main() function; here are other ways to do that:

static void Main(string[] args){}
static void Main(){}
int void Main(string[] args){}
int void Main(){}

Notice that we can call the Main() function with or without arguments. We can also make it return an integer value instead of being void. This integer value is sometimes referred to as the exit code. If the function returns with no errors, the exit code should be 0, while if some error happens, a non-zero code is returned, signifying the type of error that happened. It’s totally up to you, the programmer, to specify which code you want the Main() function to return.

The string[] array is used when you want your program to accept command line arguments. Those are parameters passed to the application from the command line, and they are one way of passing information to the code from outside the application If you use the Windows command line, you’ve probably already came across command line argument. For example typing “C:\Program Files\Internet Explorer\iexplore.exe” www.google.com on the command line will open Microsoft Internet Explorer and make it open www.google.com instead of the home page. Any command line arguments passed to the application are stored in the args[] string array and ready for you inside the function body. Have a look at this:

static void Main(string[] args)
        {
            int i = 1;
            foreach (string a in args)
            {
                Console.WriteLine("Argument " + i.ToString() + " " + a);
                i++;
            }
            Console.ReadLine();
        }

Before you run this code, you have to instruct Visual Studio that you want to pass command line arguments to the application, since it is hosted inside VS environment. In a real world application, those arguments should be passed on the command line after the application executable file.

In your Visual Studio, double click on the properties button located in the right pane as shown:
1

Then in the debug section, enter the command line arguments you wish to pass to the application. You can add any number of values separated by spaces.
2

If you run the application, you will see output similar to the following:

Argument 1 ahmed
Argument 2 mostafa
Argument 3 hussein

As you can see, we simply looped over the arguments contained in the args[] array and printed them to the screen. We used an integer variable just to make the output look prettier. The integer i is initialized by 1 and adds 1 on every iteration to indicate the argument number.

Using functions inside structures

In a previous article we talked about structures, and how they can be used to hold multiple variables. Guess what? It can hold functions too! Imagine the power and flexibility you acquire when you can use a function that is defined inside a variable. Consider the following example to get a clearer idea of what I mean:

struct student
        {
            public string firstname;
            public string lastname;

            public string fullname()
            {
                return firstname + " " + lastname;
            }
        }
        static void Main(string[] args)
        {
            student johndoe = new student();
            johndoe.firstname = "John";
            johndoe.lastname = "Doe";
            Console.WriteLine(johndoe.fullname());
            Console.ReadLine();
        }

This code will return “John Doe”, which is the student’s full name. Notice here how we defined the function inside the structure: it’s defined just like any other function, but it has access to the local variables inside the struct. You can do all sorts of processing on a struct function, like special formatting, for example, before returning the result to the calling code.

Conclusion

In this article, we discussed variable scopes, and how a variable can be local within a block, independent of variables defined outside the block, even if they have the same name. Examples of code blocks include function, loops, and if condition statements.

Then we revisited the Main() function, and saw different ways of calling it, how to pass arguments to it to make them available to the code from outside the application. Also, how to make the Main() function return an integer value indicating whether the application exited cleanly or an error happened.

Finally, we discovered a new feature in structs: they can contain functions that have access to all the local variables inside the struct. We saw how this can be used, for example, to process the data in the struct before returning it to the calling code.

In the next article, we will briefly discuss function delegates, then we can start learning about debugging and error handling in C#. Stay tuned.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -