Creating a List of a custom class

written by Ryan Olshan on Wednesday, January 11 2006

Let's say for instance, you want to create a List of your own class, say Employee, where Employee represents an employee. First, we'll start by creating an employee class.

[Serializable]
public class
Employee
{
   private bool m_IsSalaried;
   private int m_Age;
   private string m_Email;
   private string m_Name;

   public Employee(bool isSalaried, int age, string email, string name)
   {
      m_Age = age;
      m_Email = email;
      m_IsSalaried = isSalaried;
      m_Name = name;
   }

   public int Age
   {
      get { return m_Age; }
      set { m_Age = value; }
   }

   public string Email
   {
      get { return m_Email; }
      set { m_Email = value; }
   }

   public bool IsSalaried
   {
      get { return m_IsSalaried; }
      set { m_IsSalaried = value; }
   }

   public string Name
   {
      get { return m_Name; }
      set { m_Name = value; }
   }
}

You can then add an employee to a List collection as follows:

using System.Collections.Generic;

...

List<Employee> m_EmployeeList = new List<Employee>();
m_EmployeeList.Add(new Employee(true, 30, "jane @ janedoe.com", "Jane Doe"));

You can get values for Employees in the List collection by enumerating through the Employees.

foreach (Employee employee in m_EmployeeList)
{
   SomeBool = employee.IsRetired;
   SomeInt = employee.Age;
   SomeString1 = employee.Email;
   SomeString2 = employee.Name;
}

Kick this post on .NET Kicks

Similar Posts

  1. Nullable Types
  2. Implicit and Explicit Operators in C#
  3. Inheritence with Generics

Post a comment