• Startseite
  • Tutorials
  • Kontakt
  • Mein Account
Panjutorials
  • Startseite
  • Tutorials
  • Kontakt
  • Mein Account

Local vs global variables in CSharp

In this article, you’ll learn the difference between local and global variables in CSharp, and why it’s so important to know it. Local variables: are variables which are only visible within a function. They are not visible from the outside and are also only used within the function in which they were created. Global variables are variables that have been created outside of any function, but inside the class (preferably at the beginning of the class). The global variables can be seen by all functions of the same class and can also be changed within it, unless the variable is defined differently (for example, as a constant). Sometimes it happens that you want to have a variable, which can not change its value after it was once set. Then you use a “constant”. This makes e.g. sense for PI. PI does not change, but always remains the same. Let’s take a look at this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PanjutorialsHighscore
{
    class Program

    {
        static int myGlobalVariable = 15;
        static int testVariable = 10;
        const double pi = 3.14159;

        static void Main(string[] args)
        {
            myFunction(25);
            Console.WriteLine("global testVariable " + testVariable);
            Console.Read();
        }

        static void yFunction(int testVariable)
        {
            int myLocalVariable = 10;
            Console.WriteLine("global " + yGlobalVariable);
            Console.WriteLine("lokal " + myLocalVariable);

            // testVariable from the parameter
            Console.WriteLine("lokal testVariable " + testVariable);
                  
        }
    }
}

As output we receive:

Global 15

Local 10

Local testVariable 25

Global testVariable 10

If we try to use the variable myLocalVariable outside of the function, we get an error. This is simply  not allowed in CSharp. Why is the testVariable once 25 and once even after it was set to 25 it is 10? Because we used the local testVariable once (the 25) and the global (10) once . So you see that you have to pay attention to how to setup and use your variables.