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 about Variable Scope
check the Introduction to Programming Course read more
Local Variables
Local variables are declared within 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
Instance Variables
Instance variables (also called fields), are declared within a class but outside of 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
Static Variables
Static variables are declared with the static
keyword and belong to the class (instead of to 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