Home Page
"Join my free Amazing ASP.NET newsletter"
It's safe and easy to signup. You get:
  • Notified anytime a new article comes out
  • Technical step-by-step tutorials on all important ASP.NET topics
  • Expert guidance so you can reach unlimited ASP.NET success
  • Important ASP.NET news updates
Enter your Email

Click here to download the source code for this lesson.  Please note that in this zip file the example code is in the file VariableScope.cs.

In this lesson, I will talk about C# variable scope.  Whenever you declare a variable in a C# program, it will always have a scope.  The scope of a variable controls where you can and cannot reference that variable in the program.  You might have heard the expression “a variable is out of scope” before.  That means that you are trying to use a variable outside of its legal scope and the C# compiler will not allow that.  I will show you examples of that below.

Let’s start by looking at some example code for a class that I created.  The class is called VariableScope and is in the file VariableScope.cs.  In the following class, I am declaring four different variables and each one of them has a different scope which I will explain further below.

public class VariableScope
{
    int mTotal = 0;

    public void IncrementTotal()
    {
        mTotal++;
    }

    public int GetTemperature()
    {
        int iCurrentTemp = 33;

        return iCurrentTemp;
    }

    public void PerformUpdate()
    {
        for (int i = 0; i < 5; i++)
        {
            string loopvar = "Local to the loop";
        }

        if (1 == 1)
        {
            int ifvar = 55;
        }

    }
}

The first variable that I declared is “mTotal”.  This variable is declared at the class level.  A class level variable can essentially be used anywhere within its containing class.  These types of variable declarations essentially create global variables within a class.  That means that every method of the class can reference and access this type of variable.  A class level variable’s scope is the entire class.  A class level variable goes out of scope whenever its containing class is no longer being referenced, so in other words whenever the class is finished being used.  I cannot reference the variable “mTotal” anywhere outside the class.  So if I had code in a different class that uses this class VariableScope, I would not be able to refer to the variable mTotal.

The second variable is “iCurrentTemp”.  This variable is declared inside a method and its scope is local to the method within which it was declared.  This means that iCurrentTemp cannot be referenced in any other method of the class.

The third variable is “loopvar”.  This variable is local to the for loop that I declared it in.  As soon as the loop finishes, I cannot use that variable any more.

The fourth variable is “ifvar”.  This variable is local to the if statement that I declared it in.  As soon as the if statement finishes, I cannot use that variable any more.

You may have noticed a pattern here.  In order to determine the scope of a variable, look at where it is declared and then go up and look at where the first open curly brace { is.  The first place where you find the curly brace, will tell you where the scope of the variable begins.  For example look at the variable iCurrentTemp.  If you look to see where the first curly brace is, you will find that it is at the beginning of the method GetTemperature.  That means that the scope of iCurrentTemp is at the method level.

Every variable in a C# program will eventually go out of scope, so it is important to notice what the scope of a variable is when you are writing code and make sure you choose the right scope.  Here are some guidelines.

  • If you need a variable that can easily share data across various methods of the class, declare a class level variable.
  • If you a variable that will help a class maintain state, declare a class level variable.
  • If you need a variable that you only need for a specific purpose and don’t need to share it between methods, declare a method level variable.  *Keep in mind that method level variables can actually be shared between methods by passing them as parameters, but that requires more coding.  So if you have a variable that is passed around a lot as a parameter, you should consider making that variable a class level variable.
  • If you need a variable for just a very short time and for a very specific purpose, consider declaring it inside a loop or an if statement, or any other C# statement.  These are block level variables because they are only valid within a block of code.

Another thing I wanted to mention before I talk about the video is that sometimes I notice certain students who are new to the C# language get confused about variables with the same name, but that are actually declared in different contexts or blocks of code.  For example, take a look at the variable iCurrentTemp.  If I created another method and declared another variable called iCurrentTemp, those would be two completely different variables with no relationship at all.

public int GetTemperature()
    {
        int iCurrentTemp = 33;

        return iCurrentTemp;
    }

public int GetTemperatureCelsius()
    {
        int iCurrentTemp = 17;

        return iCurrentTemp;
    }

The variable name iCurrentTemp is used two times above, but the two variables are completely different.  Each one has a method level scope and they are local to their containing methods.  If you change iCurrentTemp in GetTemperature, it will not affect iCurrentTemp in GetTemperatureCelsius.

Watch the following video to see how I attempt to use all of the variables talked about in this lesson.  You will notice that I am able to use the class level variable mTotal anywhere inside the class.  For the other three variables however, when I try to use them outside of their scope, I receive a compiler error message.

This video shows me experimenting with variable scope and shows that I am unable to reference variables when they are out of scope.

Don’t forget what I mentioned about the curly braces and finding the open curly brace above a variable declaration to determine its scope.  A variable is only alive while it is still in scope.  When a variable goes out of scope, it can no longer be referenced or used at all and is essentially gone to the program.

Did you enjoy this article? Join my free Amazing ASP.NET newsletter.
It's safe and easy to signup. Unleash your unlimited web programming potential. You get:
  • Notified anytime a new article comes out
  • Technical step-by-step tutorials on all important ASP.NET topics
  • Expert guidance so you can reach unlimited ASP.NET success
  • Important ASP.NET news updates
Enter your Email

2 Comments »

  1. […] lesson is also related to a recent article that I wrote called the Scope of C# variables.  Go back and read that first if you haven’t already done so.  You need to understand how […]

    Pingback by CSharp University - practical C# and ASP.NET online learning portal » .NET and C# Garbage Collection — February 18, 2009 @ 1:49 pm

  2. please mention here why it is essential to declare variable before its use in C#,becoz in VB.net it is not mandatory.
    Article is good
    thanx

    Comment by Sushma — August 8, 2009 @ 12:21 am

RSS feed for comments on this post. TrackBack URL

Leave a comment