.Net Links

Monday, April 2, 2012

Scope of Static and Local Variable by an Example


Program





using System;
using System.Collections.Generic;
using System.Text;


namespace Winform_Events
{
     
    class Static_Variables
    {
       private static int x = 1;

       public static void Main(string[] args)
        {
            int x = 5; // method's local variable x hides static variable x


            Console.WriteLine("local x in method Main is {0}", x);


            // UseLocalVariable has its own local x
            UseLocalVariable();


            // UseStaticVariable uses class Scope's static variable x
            UseStaticVariable();


            // UseLocalVariable reinitializes its own local x
            UseLocalVariable();


            // class Scope's static variable x retains its value
            UseStaticVariable();


            Console.WriteLine("\nlocal x in method Main is {0}", x);
            Console.ReadLine();
        }


       public static void UseLocalVariable()
       {
            
           int x = 25; // initialized each time UseLocalVariable is called


           Console.WriteLine("\nlocal x on entering method UseLocalVariable is {0}", x);
           ++x; // modifies this method's local variable x
           Console.WriteLine("local x before exiting method UseLocalVariable is {0}", x);
       } // end method UseLocalVariable


       // modify class Scope's static variable x during each call
       public static void UseStaticVariable()
       {
          
           Console.WriteLine("\nstatic variable x on entering {0} is {1}","method UseStaticVariable", x);
             x *= 10; // modifies class Scope's static variable x
           Console.WriteLine("static variable x before exiting {0} is {1}","method UseStaticVariable", x);
       } // end method UseStaticVariable


    }
}



O/P
local x in method Main is 5


local x on entering method UseLocalVariable is 25
local x before exiting method UseLocalVariable is 26


static variable x on entering method UseStaticVariable is 1
static variable x before exiting method UseStaticVariable is 10


local x on entering method UseLocalVariable is 25
local x before exiting method UseLocalVariable is 26


static variable x on entering method UseStaticVariable is 10
static variable x before exiting method UseStaticVariable is 100


local x in method Main is 5

Labels: , , , ,