C# Variable Scope

In C#, the scope of a variable refers to where in the code that variable is accessible.

Variables can have three levels of scope in C#: class level, method level, and block level.

In this article, we'll take a look at each level of scope and provide some examples.

Class Level Scope

A variable that is declared at the class level can be accessed from any method or block within that class. Here's an example:

1public class MyClass 2{ 3 private string name = "William"; 4 5 public void SayHello() 6 { 7 Console.WriteLine("Hello, " + name + "!"); 8 } 9 10 public void ChangeName(string newName) 11 { 12 name = newName; 13 } 14}

In this example, the name variable is declared at the class level, so it can be accessed from both the SayHello and ChangeName methods.

Method Level Scope

A variable that is declared within a method can only be accessed within that method. Here's an example:

1public void MyMethod() 2{ 3 int x = 10; 4 Console.WriteLine(x); 5}

In this example, the x variable is declared within the MyMethod method, so it can only be accessed within that method.

Block Level Scope

A variable that is declared within a block (i.e., a set of braces) can only be accessed within that block. Here's an example:

1public void MyMethod() 2{ 3 int x = 10; 4 5 if (x == 10) 6 { 7 string message = "x is 10"; 8 Console.WriteLine(message); 9 } 10 11 // This will not compile, as message is out of scope 12 // Console.WriteLine(message); 13}

In this example, the message variable is declared within the if block, so it can only be accessed within that block.