Skip to main content

Posts

Showing posts from 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() { 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( strin

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. F