Scopes in C# | Variables Scope in C# | C# Tutorials | Learn C#

Опубликовано: 23 Октябрь 2024
на канале: Code With Cougar
124
4

The part of the program where a particular variable is accessible is termed as the Scope of that variable. A variable can be defined in a class, method, loop etc. In C/C++, all identifiers are lexically (or statically) scoped, i.e. scope of a variable can be determined at compile time and independent of the function call stack. But the C# programs are organized in the form of classes.
So C# scope rules of variables can be divided into three categories as follows:
• Class Level Scope
• Method Level Scope
• Block Level Scope

Class Level Scope
Declaring the variables in a class but outside any method can be directly accessed anywhere in the class.
These variables are also termed as the fields or class members.
Class level scoped variable can be accessed by the non-static methods of the class in which it is declared.
Access modifier of class level variables doesn’t affect their scope within a class.
Member variables can also be accessed outside the class by using the access modifiers.



Method Level Scope
A variable declared within a method has a method level Scope. It is also known as a local variable of the method where it is declared. It cannot be accessed outside the method.

Any nested code blocks within the method can access this type of variable. It cannot be declared twice with the same name within the same scope.

The local variable's scope ends when the method execution completes, and they will be collected by the garbage collector.


Code-Block Level Scope
A variable declared within a loop or any block within brackets has the code-block level scope. A variable declared within a loop or code block cannot be accessed outside of it, whereas a variable declared outside of the loop can be accessible within the loop.



#CodeWithCougar
Please Subscribe to Code With Cougar:
   / @code-with-cougar