static variables in C#

Static Variables

The static variables are declared with the static keyword. It comes to life before execution of the static
constructor for the type in which it is defined. The life of the static variable loses its existence when the
associated application domain loses its existence. The initial value of a static variable is the default value
of the variable’s type. 

Example of the Static Variables
Code Snippet
  1. using System;
  2. namespace Ch01
  3. {
  4.     class Program
  5.     {
  6.         public static int X = 100;      /* Static variable */
  7.         static void Main(string[] args)
  8.         {
  9.             Console.Write("{0}\t", X);       /* 100 */
  10.             Program.X = 200;                 /* This change affect globally */
  11.             Console.Write("{0}\t", X);       /* 200 */
  12.             Show();
  13.         }
  14.         static void Show()
  15.         {
  16.             Console.Write("{0}\t", Program.X);   /* 200 */
  17.         }
  18.     }
  19. }

This program will produce the output:
100     200     200

Post a Comment