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)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.
{
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));
}
}
We somehow need to make the collection typed, enter generics ...
static void Main(string[] args)Now you specify the type expected in the list on declaration and attempting to add the wrong type will cause a compile-time error.
{
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));
}
}
No comments:
Post a Comment