Open In App

Scope of Variables in C#

Last Updated : 19 Jan, 2019
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Example:




// C# program to illustrate the
// Class Level Scope of variables
using System;
  
// declaring a Class
class GFG { // from here class level scope starts
  
    // this is a class level variable
    // having class level scope
    int a = 10;
  
    // declaring a method
    public void display()
    {
        // accessing class level variable
        Console.WriteLine(a);
  
    } // here method ends
  
} // here class level scope ends


Method Level Scope

  • Variables that are declared inside a method have method level scope. These are not accessible outside the method.
  • However, these variables can be accessed by the nested code blocks inside a method.
  • These variables are termed as the local variables.
  • There will be a compile-time error if these variables are declared twice with the same name in the same scope.
  • These variables don’t exist after method’s execution is over.

Example:




// C# program to illustrate the
// Method Level Scope of variables
using System;
  
// declaring a Class
class GFG { // from here class level scope starts
  
    // declaring a method
    public void display()
  
    { // from here method level scope starts
  
        // this variable has
        // method level scope
        int m = 47;
  
        // accessing method level variable
        Console.WriteLine(m);
  
    } // here method level scope ends
  
    // declaring a method
    public void display1()
  
    { // from here method level scope starts
  
        // it will give compile time error as
        // you are trying to access the local
        // variable of method display()
        Console.WriteLine(m);
  
    } // here method level scope ends
  
} // here class level scope ends


Block Level Scope

  • These variables are generally declared inside the for, while statement etc.
  • These variables are also termed as the loop variables or statements variable as they have limited their scope up to the body of the statement in which it declared.
  • Generally, a loop inside a method has three level of nested code blocks(i.e. class level, method level, loop level).
  • The variable which is declared outside the loop is also accessible within the nested loops. It means a class level variable will be accessible to the methods and all loops. Method level variable will be accessible to loop and method inside that method.
  • A variable which is declared inside a loop body will not be visible to the outside of loop body.

Example:




// C# code to illustrate the Block
// Level scope of variables
using System;
  
// declaring a Class
class GFG
  
{ // from here class level scope starts
  
    // declaring a method
    public void display()
  
    { // from here method level scope starts
  
        // this variable has
        // method level scope
        int i = 0;
  
        for (i = 0; i < 4; i++) {
  
            // accessing method level variable
            Console.WriteLine(i);
        }
  
        // here j is block level variable
        // it is only accessible inside
        // this for loop
        for (int j = 0; j < 5; j++) {
            // accessing block level variable
            Console.WriteLine(j);
        }
  
        // this will give error as block level
        // variable can't be accessed outside
        // the block
        Console.WriteLine(j);
  
    } // here method level scope ends
  
} // here class level scope ends




Similar Reads

C# | Variables
A typical program uses various values that may change during its execution. For example, a program that performs some operations on the values entered by the user. The values entered by one user may differ from those entered by another user. Hence this makes it necessary to use variables as another user may not use the same values. When a user ente
4 min read
C# Program to Get the Environment Variables Using Environment Class
In C#, Environment Class provides information about the current platform and manipulates, the current platform. It is useful for getting and setting various operating system-related information. We can use it in such a way that it retrieves command-line arguments information, exit codes information, environment variable settings information, conten
3 min read
C# | Implicitly Typed Local Variables - var
Implicitly typed variables are those variables that are declared without specifying the .NET type explicitly. In an implicitly typed variable, the type of the variable is automatically deduced at compile time by the compiler from the value used to initialize the variable. The implicitly typed variable concept is introduced in C# 3.0. The implicitly
4 min read
C# Tutorial
In this C# (C Sharp) tutorial, whether you’re beginner or have experience with other programming languages, our free C# tutorials covers the basic and advanced concepts of C# including fundamentals of C#, including syntax, data types, control structures, classes, and objects. You will also dive into more advanced topics like exception handling, and
8 min read
ASP.NET Interview Questions and Answer
ASP.NET is a powerful framework for building dynamic web applications, known for its scalability, performance, and integration with the .NET ecosystem, developed by Microsoft that allows developers to build dynamic web applications, websites, and services. It is part of the larger .NET framework and provides a comprehensive programming model for cr
15+ min read
C# Interview Questions and Answers
C# is the most popular general-purpose programming language and was developed by Microsoft in 2000, renowned for its robustness, flexibility, and extensive application range. It is simple and has an object-oriented programming concept that can be used for creating different types of applications. Here, we will provide 50+ C# Interview Questions and
15+ min read
Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework
Prerequisites: Download and Install Microsoft SQL Server Management StudioDownload and Setting Up Visual Studio Community Version MVC stands for Model View Controller. It is a design pattern that is employed to separate the business logic, presentation logic, and data. Basically, it provides a pattern to style web application. As per MVC, you can d
6 min read
Program to calculate Electricity Bill
Given an integer U denoting the amount of KWh units of electricity consumed, the task is to calculate the electricity bill with the help of the below charges: 1 to 100 units - [Tex]Rs. 10/unit[/Tex]100 to 200 units - [Tex]Rs. 15/unit[/Tex]200 to 300 units - [Tex]Rs. 20/unit[/Tex]above 300 units - [Tex]Rs. 25/unit[/Tex] Examples: Input: U = 250 Outp
9 min read
Garbage Collection in C# | .NET Framework
Garbage collection is a memory management technique used in the .NET Framework and many other programming languages. In C#, the garbage collector is responsible for managing memory and automatically freeing up memory that is no longer being used by the application. The garbage collector works by periodically scanning the application's memory to det
8 min read
Extension Method in C#
In C#, the extension method concept allows you to add new methods in the existing class or in the structure without modifying the source code of the original type and you do not require any kind of special permission from the original type and there is no need to re-compile the original type. It is introduced in C# 3.0. Let us discuss this concept
5 min read
HashSet in C# with Examples
In C#, HashSet is an unordered collection of unique elements. This collection is introduced in .NET 3.5. It supports the implementation of sets and uses the hash table for storage. This collection is of the generic type collection and it is defined under System.Collections.Generic namespace. It is generally used when we want to prevent duplicate el
6 min read
C# Dictionary with examples
In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.Collections.Generic namespace. It is dynamic in nature means the size of the dictionary is growing
5 min read
Difference between Ref and Out keywords in C#
The out is a keyword in C# which is used for the passing the arguments to methods as a reference type. It is generally used when a method returns multiple values. The out parameter does not pass the property. Example : // C# program to illustrate the // concept of out parameter using System; class GFG { // Main method static public void Main() { //
3 min read
Difference between Abstract Class and Interface in C#
An abstract class is a way to achieve abstraction in C#. To declare an abstract class, we use the abstract keyword. An Abstract class is never intended to be instantiated directly. This class must contain at least one abstract method, which is marked by the keyword or modifier abstract in the class definition. The Abstract classes are typically use
4 min read
C# | Arrays of Strings
An array is a collection of the same type variable. Whereas a string is a sequence of Unicode characters or array of characters. Therefore arrays of strings is an array of arrays of characters. Here, string array and arrays of strings both are same term. For Example, if you want to store the name of students of a class then you can use the arrays o
4 min read
Collections in C#
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr&gt;th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } Collectio
5 min read
Introduction to .NET Framework
The .NET Framework is a software development framework developed by Microsoft that provides a runtime environment and a set of libraries and tools for building and running applications on Windows operating systems. The framework includes a variety of programming languages, such as C#, F#, and Visual Basic, and supports a range of application types,
7 min read
Common Language Runtime (CLR) in C#
The Common Language Runtime (CLR) is a component of the Microsoft .NET Framework that manages the execution of .NET applications. It is responsible for loading and executing the code written in various .NET programming languages, including C#, VB.NET, F#, and others. When a C# program is compiled, the resulting executable code is in an intermediate
6 min read
C# | List Class
.list-table { border-collapse: collapse; width: 100%; } .list-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .list-table th { border: 1px solid #5fb962; padding: 8px; } .list-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .list-table tr:nth-child(odd) { background-color: #ffffff; } List&lt;T
7 min read
C# | Encapsulation
Encapsulation is defined as the wrapping up of data and information under a single unit. It is the mechanism that binds together the data and the functions that manipulate them. In a different way, encapsulation is a protective shield that prevents the data from being accessed by the code outside this shield. Technically in encapsulation, the varia
5 min read
C# | Method Overriding
Method Overriding in C# is similar to the virtual function in C++. Method Overriding is a technique that allows the invoking of functions from another class (base class) in the derived class. Creating a method in the derived class with the same signature as a method in the base class is called as method overriding. In simple words, Overriding is a
8 min read
Hello World in C#
The Hello World! program is the most basic and first program when you dive into a new programming language. This simply prints the Hello World! on the output screen. In C#, a basic program consists of the following: A Namespace DeclarationClass Declaration &amp; DefinitionClass Members(like variables, methods etc.)Main MethodStatements or Expressio
3 min read
C# | How to check whether a List contains a specified element
List&lt;T&gt;.Contains(T) Method is used to check whether an element is in the List&lt;T&gt; or not. Properties of List: It is different from the arrays. A list can be resized dynamically but arrays cannot.List class can accept null as a valid value for reference types and it also allows duplicate elements.If the Count becomes equals to Capacity th
2 min read
C# | Delegates
A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. Delegates in C# are similar to the function pointer in C/C++. It provides a way which tells which method is to be called when an event is triggered. For example, if you click on a Button on a form (Windows Form a
6 min read
C# | Inheritance
Introduction: Inheritance is a fundamental concept in object-oriented programming that allows us to define a new class based on an existing class. The new class inherits the properties and methods of the existing class and can also add new properties and methods of its own. Inheritance promotes code reuse, simplifies code maintenance, and improves
7 min read
C# | Generics - Introduction
Generic is a class which allows the user to define classes and methods with the placeholder. Generics were added to version 2.0 of the C# language. The basic idea behind using Generic is to allow type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes, and interfaces. A primary limitation of collections is the abs
6 min read
C# | Substring() Method
In C#, Substring() is a string method. It is used to retrieve a substring from the current instance of the string. This method can be overloaded by passing the different number of parameters to it as follows: String.Substring(Int32) Method String.Substring(Int32, Int32) Method String.Substring Method (startIndex) This method is used to retrieves a
3 min read
C# | Arrays
An array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float, etc. and the elements are stored in a contiguous location. Length of the array specifies the number of elements present in the array
13 min read
C# | Constructors
A constructor is a special method of the class which gets automatically invoked whenever an instance of the class is created. Like methods, a constructor also contains the collection of instructions that are executed at the time of Object creation. It is used to assign initial values to the data members of the same class. Example : class Geek { ...
6 min read
C# | Data Types
Data types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C#, each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given program must be described with one of the data type
7 min read
Article Tags :