Variable Scopes in C#
680
10-Jun-2024
Updated on 10-Jun-2024
Ravi Vishwakarma
10-Jun-2024In C#, variable scope refers to the accessibility and lifetime of variables within a program.
Here are the common variable scopes in C#:
Global Scope: Variables declared outside of any method, typically at the class level, have global scope. They are accessible from any method within the class.
Local Scope: Variables declared within a method have local scope. They are accessible only within the method where they are declared.
Block Scope: Variables declared within a block of code (within curly braces
{}) have block scope. They are accessible only within that block.Class Scope (Static Variables): Static variables declared within a class have class scope. They are accessible to all instances of the class.
Method Parameters: Parameters passed to a method have scope within that method.
Lambda Expressions and Anonymous Methods: Variables used within lambda expressions and anonymous methods have access to variables in the outer scope, but they must be effectively final (cannot be modified within the lambda/anonymous method).