Anonymous Method to Retrieve Data Reader Passed from DAL

Some time you are forced to create a method just for the sake of using a delegate, for example there is no need for multiple targets or the code involved too short and simple. Anonymous method is a new feature in C# 2.0 that allows you to define an anonymous method called by a delegate. While they are new to C# world its widely used as "Closers" in functional programming language like lisp.

When we pass DataReader from DAL to business layer or UI we are also passing responsibility of closing connection to client, in case of unexpected error or if some body working on UI forgets to close reader then connection will remain open.

Few months ago "Teemu Keiski" came up with excellent way of using delegates to Control DAL responsibility. You can read more about his technique here. Lots of people shed away from using his technique because it needs additional method to be declared to retrieve DataReader passed as delegate parameter. But with the introduction of anonymous methods there is no need to write additional method.

I am using "Northwind" database to show sample code.

Following is DAL code with DataReaderHandler delegate and GetCustomer method that takes delegate. DAL code takes care of closing reader and connection.

public class CustomerDB
public delegate void DataReaderHandler(IDataReader reader);
public static void GetCustomer(DataReaderHandler handler, string customerID)
string connectionString = "server=localhost;Trusted_Connection=true;database=NorthWind";
using (SqlConnection conn = new SqlConnection(connectionString))
SqlCommand sqlCommand =
new SqlCommand("Select * from Customers WHERE CustomerID = @CustomerID", conn);
sqlCommand.Parameters.AddWithValue("@CustomerID", customerID);
using (SqlDataReader rdr = sqlCommand.ExecuteReader(CommandBehavior.CloseConnection))

How to access GetCustomer from client side.

CustomerDB.GetCustomer(delegate(IDataReader reader){
// do some this with code.
}, "ALFKI");

Read more about new features in c# 2.0 here.

Attached code contains sample DAL class and method code, for simplicity I have kept both on same aspx page.