February 23, 2007

Playing with Generics

I've been meaning to play with Generics more for a long time now. I finally have the chance.

As part of a new project we are working on we are using the Generic List class all over the place.

A common usage is to store a Contact class. It has the standard stuff: first name, last name, address, bank account, gun locations, caliber of gun, etc.

Now we want to sort them by by weird criteria like amount of money in house, number of guns, and caliber. (note to self: I should also save amount of ammo) Or see if a contact exists with no guns at all. Very standard stuff.

So, in the List class there are now Predicates for both the Find and Exists methods. Using Predicates and anonymous delegates you can pass custom code into the Find method. Essencially telling the Find method how to find something.

So it would look like this:

Contact found = currContacts.Find(
delegate(Contact c)
{
// has no guns and more than 5 dollars
if ((c.Gun.Count == 0) && (c.NetWorth > 5.0)
return true;
else
return false;
});

But for something more likely, and powerful. Say you are moving new items to list of existing items. Say I have a list of new contacts, but first I have to figure out if the contact doesn't already exist. To do this you have to find contacts with the same first name and last name.

List currContacts = GetAllContacts();

foreach(Contact newContact in contactList)
{
Contact found = currContacts.Find(
delegate(Contact c)
{
if ((c.FirstName == newContact.FirstName)
&& (c.LastName == newContact.LastName)
return true;
else
return false;
});

if (found != null)
{
currContact.Add(newContact);
}
}


Finally, I've been looking into Generic methods. You can have a single method in a class that uses generics, without making any changes to any other part of the class. Very cool! Here is an example:

public T MaxValue(T currentValue, T newValue)
{
if ((currentValue > newValue)
return currentValue ;
else
return newValue;
}

This is making much of my life much simpler.

No comments: