Creating a List of a custom class
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 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;
}