instance variables in C#


Instance Variables

A field declared without the static modifier is called an instance variable. Listing 1-13 shows an example
of the instance variable.


Example of the Instance Variables

Code Snippet
  1. using System;
  2. namespace Ch01
  3. {
  4.     class Program
  5.     {
  6.         static void Main(string[] args)
  7.         {
  8.             AClass anObject = new AClass();
  9.             Console.ReadLine();
  10.         }
  11.     }
  12.     public class AClass
  13.     {
  14.         public int X;
  15.         public AClass()
  16.         {
  17.             Console.WriteLine("Initial value of the X :{0}", X);
  18.             X = 100;
  19.             Console.WriteLine("Updated value of the X :{0}", X);
  20.             MethodA();
  21.         }
  22.         public void MethodA() { }
  23.     }
  24. }

This program will produce the output:
Initial value of the X :0
Updated value of the X :100

Instance Variables in Classes

An instance variable of a class comes to life when a new instance of that class is instantiated. In addition, it
will no longer exist when there are no references to that instance and the instance’s destructor (if any) has
executed.

Instance Variables in Structs

An instance variable of a struct has exactly the same lifetime as the struct type variable to which it
belongs.

Post a Comment