In C#, the Scope of the variable determines the accessibility of the variable to a particular part of the application. Variables can be declared within the class, method, and code block of a loop, condition, etc.
There are three types of scopes in C#.
- Class Level Scope
- Method Level Scope
- Code-Block Level Scope
Class Level Scope
A variable declared within a class is known as a field. It has a class-level scope that can be accessed anywhere in the class, such as class methods, properties, etc.
In the above example, the
The class level variables can also be accessed out of class using class objects depending on the access modifiers. The static variables of the class can only be accessed from the static methods or properties.
There are three types of scopes in C#.
- Class Level Scope
- Method Level Scope
- Code-Block Level Scope
Class Level Scope
A variable declared within a class is known as a field. It has a class-level scope that can be accessed anywhere in the class, such as class methods, properties, etc.
In the above example, the
Student
class contains two class variables (a.k.a. fields) _firstName
and _lastName
. These fields can be accessed anywhere within the class, i.e., within any non-static methods and properties.The class level variables can also be accessed out of class using class objects depending on the access modifiers. The static variables of the class can only be accessed from the static methods or properties.