static property used to maintain a count of the number of Employee objects that have been created. - CSharp Custom Type

CSharp examples for Custom Type:Property

Description

static property used to maintain a count of the number of Employee objects that have been created.

Demo Code



using System;//from   w ww . j a v a  2  s.c  o  m

class Employee
{
   public static int Count { get; private set; } // objects in memory

   public string FirstName { get; }
   public string LastName { get; }

   // initialize employee, add 1 to static Count and
   // output string indicating that constructor was called
   public Employee(string firstName, string lastName)
   {
      FirstName = firstName;
      LastName = lastName;
      ++Count; // increment static count of employees
      Console.WriteLine("Employee constructor: " +
         $"{FirstName} {LastName}; Count = {Count}");
   }
}


public class MainClass
{
   static void Main()
   {
      // show that Count is 0 before creating Employees
      Console.WriteLine($"Employees before instantiation: {Employee.Count}");

      // create two Employees; Count should become 2
      var e1 = new Employee("A", "C");
      var e2 = new Employee("B", "V");

      // show that Count is 2 after creating two Employees
      Console.WriteLine($"\nEmployees after instantiation: {Employee.Count}");

      Console.WriteLine($"\nEmployee 1: {e1.FirstName} {e1.LastName}");
      Console.WriteLine($"Employee 2: {e2.FirstName} {e2.LastName}");

      e1 = null; // mark object referenced by e1 as no longer needed
      e2 = null; // mark object referenced by e2 as no longer needed
   }
}

Result


Related Tutorials