Instance versus static members - CSharp Language Basics

CSharp examples for Language Basics:Data Type

Introduction

In the following code, the instance field Name pertains to an instance of a particular Animal, whereas Population pertains to the set of all Animal instances:

Demo Code

using System;/*www .  ja v  a  2  s  . c  o m*/
class Animal
{
   public string Name;             // Instance field
   public static int Population;   // Static field
   public Animal (string n)         // Constructor
   {
      Name = n;                     // Assign the instance field
      Population = Population + 1;  // Increment the static Population field
   }
}
class Test
{
   static void Main()
   {
      Animal p1 = new Animal ("A");
      Animal p2 = new Animal ("B");
      Console.WriteLine (p1.Name);      // A
      Console.WriteLine (p2.Name);      // B
      Console.WriteLine (Animal.Population);   // 2
   }
}

Result


Related Tutorials