The power of delegate
Last time I have an opportunity to build a small example which shown me the big power of delegate.This example has focused on getting data from database. I wanted to build a method which would show me all data from any table. The first thing which I did, was
building a class which mapes the database table into class for example:
8 public class Person
9 {
10 int id;
11 string name;
12 string surname;
13 List<Address> addresses;
14
15 public List<Address> Addresses
16 {
17 get { return new AddressDAO().GetAddressesByPersonId(this.id); }
18 set { addresses = value; }
19 }
20
21 public int Id
22 {
23 get { return id; }
24 set { id = value; }
25 }
26
27 public string Name
28 {
29 get { return name; }
30 set { name = value; }
31 }
32
33 public string Surname
34 {
35 get { return surname; }
36 set { surname = value; }
37 }
38
39 public Person(int id, string name, string surname)
40 {
41 this.id = id;
42 this.name = name;
43 this.surname = surname;
44 }
45 }
When I have it done the next thing was building a DAOTemplate class which has couple methods like: query, execute. In fact I will just focused on query method. I want to use this method to get a data from any database table. This method takes two parameters string query where we put our query and delegate which will create a generic list with our data.
The query method looks like:
20 public void Query(string query, RowCallBackHandler del)
21 {
22 this.con.Open();
23 OdbcCommand cmd = this.con.CreateCommand();
24 cmd.CommandText = query;
25
26 OdbcDataReader rdr = cmd.ExecuteReader();
27 while (rdr.Read())
28 {
29 del(rdr);
30 }
31 this.con.Close();
32 }
As you can see, I open connection, next create command and execute it. Next I launch a while loop to get all results from datareader and pass them to delegate. It is pretty easy.
The last step is building ADO layer for Person table:
13 public List<Person> GetPeople()
14 {
15 List<Person> people = new List<Person>();
16 DAOTemplate template = DAOManager.GetDaoTemplate();
17
18 template.Query("select * from Person", delegate( OdbcDataReader rdr)
19 {
20 Person person = new Person (rdr.GetInt32(0), rdr.GetString(1), rdr.GetString(2));
21 people.Add(person);
22 });
23
24 return people;
25 }
Now when I invoke the method GetPeople it means I will invoke the template.Query method inside, with two parameters, first - the query which gives me all person and the second parameter - anonymous callback method. This second parameter it responsibles for adding a new person to my list of people.
The best way to see the true power of callbacks is execute this example yourself.