C# delegates are fun

Apr 03, 2009 14:49

For demonstration, let's use this class Person.

class Person
{

public string firstName = String.Empty;
public string lastName = String.Empty;

Person()
{
}

}

Person is a basic class.  It has two public members, firstName and lastName and an empty constructor.  Now let's say in our program, we have a List of our class:

List
personList = new List
();

Now let's assume we populate that list somewhere in our program and we get the the following data:

"John", "Smith"
"Jim", "Johnson"
"April", "Jones"
"Jon", "Thomas"
"Marie", "Jones"
"Rutiger", "Oppenheimer"
"Jon", "Smith"
"Jim", "Smith"

Now imagine if you wanted to change the values for Rutiger Oppenheimer.  There was a mistake somewhere, and the last name should read "Thompson" instead of "Oppenheimer".  Now if you don't know where in the list this person is, how would you accomplish this?  Most people would probably write something like:

for(int i = 0; i < personList.Count; i++)
{
if(personList[i].lastName == "Oppenheimer")
personList[i].lastName = "Thompson";
}
A basic for loop.  This accompishes the desired task, but on a larger scale or repeating a similar task several times gets to be a lot of loops, the code gets messy, etc.  This task can be accomplished a lot easier using delegates:

Person personDelegate = personList.Find(delegate(Person p) { return p.lastName == "Oppenheimer"; });
personDelegate.lastName = "Thompson";

Done.  2 lines of code.  Granted this is a fairly trivial example.  However in much larger scale scenarios, delegates can be very helpful.
Previous post Next post
Up