Scope class demonstrates static and local variable scopes. - CSharp Custom Type

CSharp examples for Custom Type:static

Description

Scope class demonstrates static and local variable scopes.

Demo Code

using System;/*from  w w w.  j a v a  2 s. co  m*/
class Scope
{
   private static int x = 1;
   static void Main()
   {
      int x = 5; // method's local variable x hides static variable x
      Console.WriteLine($"local x in method Main is {x}");
      UseLocalVariable();
      UseStaticVariable();
      UseLocalVariable();
      UseStaticVariable();
      Console.WriteLine($"\nlocal x in method Main is {x}");
   }
   static void UseLocalVariable()
   {
      int x = 25; // initialized each time UseLocalVariable is called
      Console.WriteLine($"\nlocal x on entering method UseLocalVariable is {x}");
      ++x;
      Console.WriteLine($"local x before exiting method UseLocalVariable is {x}");
   }
   static void UseStaticVariable()
   {
      Console.WriteLine("\nstatic variable x on entering method " + $"UseStaticVariable is {x}");
      x *= 10; // modifies class Scope's static variable x
      Console.WriteLine("static variable x before exiting " + $"method UseStaticVariable is {x}");
   }
}

Result


Related Tutorials