Console C#.Net Tutorial

Visual Studio.NET IDE

Define C#.NET

C# Comment

C# Variables

C# Data Types

C# Escape Sequence

C# Operators

Format String

Operator Precedence

C# Keywords

Constant Variable

Type Conversion

Flow Control

C# Arrays

C# Character

C# Strings

User-Define Methods

Variable Scope

C# Enumerations

C# Structure

C# Exception Handling

Object Oriented Programming

C# Classes

Constructor & Destructor

C# Inheritance

C# Polymorphism

C# Operator Overloading

C# Method Overriding

C# Interface

Abstract Classes & Methods

Sealed Classes, Methods

C# Properties

C# Indexer

C# Delegates

C# Generics

C# Collection

C# ArrayList

C# Stack

C# Queue

C# HashTable

C# SortedList

Page Stats

Visitor: 185

C#.Net - Scope of a Variable

Variable whose scope covers a single method are known as local variable.

Variable whose scope covers multiple methods are known as global variables. In C#.Net you must use either static or const keyword for declaring a global variable. If you want to modify the value of the global variable, use static, as constant variable prohibits any change in the value of a variable.

Example 1: Local and Global variable.

using System;

namespace ConsoleApplication1
{
    class Program
    {
        //const int a = 10; //global variable
        static int a = 10; //global variable
        static void method()
        {
            int b = 20; //local variable
            Console.WriteLine("Variable inside method = " + a);
        }

        static void Main(string[] args)
        {
            int c = 20; //local variable
			a = 50;
            method();
            Console.WriteLine("Variable inside main method = " + a);
            Console.ReadLine();
        }
    }
}
Variable inside method = 50
Variable inside main method = 50