csharp-ambito-variables

What is the scope of variables in C#

  • 2 min

The scope of a variable refers to the part of the program where the variable is accessible. In C#, variables can have different scopes depending on where they are declared.

If you want to learn more, check out the Introduction to Programming Course

Local Variables

Local variables are declared inside a method and are only accessible within that method. Their lifecycle begins when the method is invoked and ends when the method finishes.

public void ExampleMethod()
{
    int number = 10; // Local variable, only exists in this method
    
    Console.WriteLine(number); // ✔️ you can use it here
}

number = 5; // ❌ this would give an error, it doesn't exist here
Copied!

Instance Variables

Instance variables (also called fields), are declared inside a class but outside any method. They are accessible by all methods of the class and their lifecycle is the same as that of the class instance.

public class Person
{
    public string name; // Instance variable

    public void ShowName()
    {
        Console.WriteLine(name);  // ✔️ you can use it here
    }
}

name = "Luis"; // ❌ this would give an error, name doesn't exist here

Person person = new Person();
person.name = "Luis"; // ✔️ this works
Copied!

Static Variables

Static variables are declared with the static keyword and belong to the class (instead of a specific instance). They are accessible without creating an instance of the class and their lifecycle lasts until the application ends.

public class Counter
{
    public static int GlobalCounter; // Static variable

    public void Increment()
    {
        GlobalCounter++;  // ✔️ you can use it here
    }
}

GlobalCounter = 10;  // ❌ this would give an error, name doesn't exist here

Counter.GlobalCounter = 10; // ✔️ this works
Copied!