Friday, November 21, 2008

Passing a Method as a Parameter

I have a library that has a number of methods similar to this:

public static DataTable GetContracts()
{
string tableName = "Contracts";
DataTable dataTable = (DataTable)Tools.GetCacheObject(tableName);
if (dataTable == null)
{
dataTable = DataObjects.Common.GetContractsFromDB();
Tools.AddToCache(tableName, dataTable);
}

return dataTable;
}


The only things that change in each one are the items shown in purple. I got to thinking that this code could be streamlined further by simply passing in 'tableName' as a parameter. But what to about the fact that the method being called in 'DataObjects.Common' changes too?

Well, thankfully C#.net has a solution for this too! And its name is "Delegate". It essentially acts as a proxy for a method, allowing a method to also be passed in as a parameter.

Here's the simple code to make this work, using the same example as above:

private delegate DataTable DBFetchDelegate();

private static DataTable GetDataTable(string tableName, DBFetchDelegate dbMethod)
{
DataTable dataTable = (DataTable)Tools.GetCacheObject(tableName);
if (dataTable == null)
{
dataTable = dbMethod();
Tools.AddToCache(tableName, dataTable);
}

return dataTable;
}

public static DataTable GetContracts()
{
return GetDataTable(
"Contracts", DataObjects.Common.GetClosedMonths);
}

No comments:

Post a Comment