Sunday, June 23, 2024 22:23

Table of contents >> Functions > Variable Scope

Variable Scope

A very important concept in programming is what we call variable scope. Though this concept should have been explained when I explained variables, it wouldn’t have made much sense back then, because it was relying on stuff we did not yet explain.

Even now, we will be using a concept we haven’t learn yet – classes – but we dealt with them before in our examples, and we said that we can view classes as a standalone object, a complete structure, self sufficient, with properties, methods and events. For instance, we can say Apple is an object, Car is an object, computer is an object and so on.

I also specified a few times that classes, just like a lot of other programming concepts I have explained already, have a body, delimited by opening and closing curly brackets. When I talked about method and functions, I said that they can only be declared inside the body of a class.

Here is a simple example of a class containing a few methods:

So, in the above code snippet, we have a class containing two functions and a method. See? It’s simple. Now we can explain the concept of variable scope. There are many kinds of scopes in C#, but for now we are only interested in two: field variables (also called members) and local variables.

The scope of a variable defines the area in which that variable is visible and accessible. In other words, a variable can be accessible from any part of the code, or not. To better understand this new concept, let’s take a look at the following example:

Analyzing the above code, we observe that we have a class called Program, with one method called Main(), and one function of type int, called Add(). In addition to them, we also have two variables: a field variable called myFieldVariable and a local variable called myLocalVariable. How can we tell if a variable is local or a field? Field variables are declared directly inside the body of a class. Local variables are always declared inside a structure in that class (method, function, property, union, etc). So, because myFieldVariable is declared directly inside our class’ body, it is a field variable. On the other hand, because myLocalVariable is declared inside the body of function Add(), it becomes a local variable. So, the scope of our variable becomes a local scope. This means that myLocalVariable is “visible” and accessible ONLY inside the method in which it was declared!

In the above example we declared myLocalVariable inside the function Add(), but we tried to use it inside the Main() method, which is impossible, since that variable is a local variable and is only visible inside the structure it was declared, in this case, function Add().

This is why we will not be able to compile and run the above code. The compiler will warn us about the following error: The name ‘myLocalVariable’ does not exist in the current context.

variable does not exist in current context

On the other hand, you see that myFieldVariable is perfectly accessible and does not generate an error. This is because a field variable – a variable that is declared inside the body of a class is “visible” and accessible anywhere inside that class, regardless if we try to access it inside a method, a function or anything else.

Additional Information

It is always a good habit to declare your field variables immediately after the opening bracket of your class, so they can be quickly and easily visible to anyone examining your code.

Now, let’s change the above code a bit. Move the declaration of myLocalVariable from inside the body of our Add() function to the body of our Main() method:

And, surprise! You compiler error will suddenly disappear and both your field and local variables become accessible. The reason for this is because myLocalVariable was declared inside our Main() method, and we try to use it also inside the Main() method, which is perfectly valid, since the scope of myLocalVariable is limited only to the Main() method’s body.

So, now that we clarified the difference between field and local scopes, lets investigate the matter a little bit more. Consider the following example:

We can observe from the above code something strange. First of all, we are declaring three int variables with the same name. How is this possible?! Shouldn’t the name conflict somehow? How can the compiler tell which one of them we want to display on the console?

The explanation is simple: local variables can be even more “local”. Just like our “day” variable is a local variable because we declared it inside the body of our DisplayMessage() method, and it’s only visible inside the body of that method, our “hour” variables, because we declared them inside the bodies of the if-else structure, they are only visible in the blocks of those if-else parts where they were declared. Examine the following image:

variable scope

So, once we declare a variable inside the body of some structure, be it a method, a function, or even an if-else construct, it is only visible inside that body delimited by the opening and closing curly brackets. This is also the reason why we can declare three variables with the same exact name. They are declared inside the body of our if-else construct, and they only live inside those bodies. They are not visible to the outside of the block where they were declared. If we have 100 blocks, we can declare a variable with the same name in each of those blocks, and they would not conflict. However:

variable scope conflict

As you can see, when we try to declare two variables with the same name in the same body, the compiler will throw an error: “A local variable or function named XXX is already defined in this scope“.

Because a variable is only visible inside the body of the structure where it was declared, our code will also generate an error. This is because:

variable scope error

Since our “hour” variables were declared inside the bodies of our if-else check, they cannot be accessible inside the DisplayMessage method, which is one “level” upper. This tells us an interesting thing: a variable declared inside the body of a construct is visible inside the body of that construct, AND inside the body of any other structure defined inside the body of our construct. On the other hand, a variable defined inside a body of a construct which was declared inside the body of another construct, is not visible to the outside construct. This is also the reason why a variable defined inside a method is not visible inside another method. This is also the reason why a variable declared inside the body of a class is visible to any construct inside that class.

Finally, there is one more thing we need to discuss. What kind of variables are the variables we declare as parameters for our functions and methods?

They are also local variables, and their scope is valid inside the whole body of the method or function that declares them.

The concepts explained in this lesson are also shown visually as part of the following video:

Tags: , ,

2 Responses to “Variable Scope”

  1. Good job says:

    Good post, keep

Leave a Reply

Follow the white rabbit