Tuesday, 18 November 2008

Example of using generics

I have done a basic example of using generics List. In the following example I have created the basic form as follows:

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 _employees = new List();
public form()
private void btnAdd_Click(object sender, EventArgs e)
var newEmployee = new Employee
firstName = txtFirstName.Text,
surname = txtSurname.Text,
age = int.Parse(txtAge.Text)
private void btnList_Click(object sender, EventArgs e)
foreach (var employee in _employees)
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.

Understanding Generics in C#

We have begun introducing generics into all of our code at work and I have found it difficult to understand, lots of 's and this sort of thing and when you multiply that across all of the project I have decided I need to get a grip on generics in C#.

My port of call was the Microsoft MSDN website, and that is what I am looking at now allthough I have 2 books as well, Beginning C# 2005 (Wrox Press) and C# In depth (Skeet).

My first question was what is the benefits of generics, I managed to survive without them before. Luckily one of the articles on the MSDN website answers this directly http://msdn.microsoft.com/en-gb/library/b5bx6xee.aspx

Obviously this article doesn't answer all of the questions it just addresses using list over arraylist however it is a start. What I hadn't realised was that when you use an arraylist is casts everything you add to the array into the object type which is both performance hungry and also allows you to run the chance of a run time error.

For example the website uses

System.Collections.ArrayList list = new System.Collections.ArrayList();
// Add an integer to the list.
// Add a string to the list. This will compile, but may cause an error later.
list.Add("It is raining in Redmond.");
int t = 0;
// This causes an InvalidCastException to be returned.
foreach (int x in list){ t += x;}

Here you would not want to be mixing to different types but if you used a generic list instead the error would have been flagged up immediately.

Comments System

Disqus Shortname