Tuesday, 30 January 2007

Generics

I am not going to even to attempt to fully cover Generics, I am guessing you can expect a great deal of questions on Generics in the exams. So I am going to cover some important stuff and leave links to the items that I have found useful.

Here goes with a simple generic's example ...

Lets say you want a collection of Person objects, a Person has a Forename & Surname property typically you would add these Person objects to an ArrayList.



static void Main(string[] args)
{
ArrayList people
= new
ArrayList();
people.Add(
new Person("Dave", "Green"
));
people.Add(
new Person("Joe", "Bloggs"
));
foreach (Person item in
people)
{
Console.WriteLine(
string.Format("{0} {1}"
, people.Forename, people.Surname));
}
}
Now this is not exactly type safe, we are assuming the ArrayList only contains Person objects, this case it does we added them but we can't always count on this. We are constantly casting & uncasting the objects, if dealing with value types we constantly box & unbox the objects in the list.

We somehow need to make the collection typed, enter generics ...

static void Main(string[] args)
{
List
<Person> people = new List<People>
();
people.Add(
new Person("Dave", "Green"
));
people.Add(
new Person("Joe", "Bloggs"
));
foreach (Person item in
people)
{
Console.WriteLine(
string.Format("{0} {1}"
, people.Forename, people.Surname));
}
}
Now you specify the type expected in the list on declaration and attempting to add the wrong type will cause a compile-time error.

No comments: