I have done a basic example of using generics List. In the following example I have created the basic form as follows:
public class Employee
{
public string firstName { get; set; }
public string surname { get; set; }
public int age { get; set; }
public int id { get; set; }
}
public partial class form : Form
{
readonly List _employees = new List();
public form()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
var newEmployee = new Employee
{
firstName = txtFirstName.Text,
surname = txtSurname.Text,
age = int.Parse(txtAge.Text)
};
_employees.Add(newEmployee);
}
private void btnList_Click(object sender, EventArgs e)
{
foreach (var employee in _employees)
{
listView1.Items.Add(
string.Format("{0} {1} {2}", employee.firstName, employee.surname, employee.age)
);
}
}
}
I then created a basic employee class that held just name, surname and age.
public class Employee
{
public string firstName { get; set; }
public string surname { get; set; }
public int age { get; set; }
public int id { get; set; }
}
This allows us to create a list of employees and using generics they will not be upcast into objects and I will not have to create any long codes of collections.
The code for the form is as follows
public partial class form : Form
{
readonly List
public form()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
var newEmployee = new Employee
{
firstName = txtFirstName.Text,
surname = txtSurname.Text,
age = int.Parse(txtAge.Text)
};
_employees.Add(newEmployee);
}
private void btnList_Click(object sender, EventArgs e)
{
foreach (var employee in _employees)
{
listView1.Items.Add(
string.Format("{0} {1} {2}", employee.firstName, employee.surname, employee.age)
);
}
}
}
It is extremely easy to just create a list of employees and because it is strongly typed you do not have to mess about when using a foreach statement.
Comments