Friday, August 6, 2010
Munq IocContainer Version 2.0
Tuesday, August 5, 2008
C# 3.0 Extension Methods
I'm getting stuck into C# 3.0 and really enjoying some of the new features. How often do you go looking for a class method to perform a specific task only to discover the method doesn't exist or exists but only does part of the job. Inevitably my programs contain methods I've created specifically to address this issue. One of the downsides of this approach is that there's often no obvious place to code the method, it just gets stuck close to where it is used or in a utility class if it is used in more than one location. And that is bad because it increases coupling/lowers cohesion for classes. Extension methods are a great way to address this situation.
I have an ASP.Net application that began life as a real application. The version I use to explore new stuff now bears little resemblance to the original but when I wrote it I was surprised to find that System.Web.UI.Control.FindControl() doesn't recurse down through the child controls. As a result I wrote the following method in the code-behind for a MasterPage:
private static Control LocateControl( Control Ctrl, string Id)
{
Control ctrlRet = Ctrl.FindControl( Id);
if (ctrlRet == null)
{
for (int i = 0; i < Ctrl.Controls.Count && ctrlRet == null; i++)
{
ctrlRet = LocateControl( Ctrl.Controls[i], Id);
}
}
return ctrlRet;
}
Using extension methods I can now instead code a new class ControlExtensions:
public static class ControlExtensions
{
public static Control LocateControl(this Control Ctrl, string Id)
{
Control ctrlRet = Ctrl.FindControl(Id);
if (null == ctrlRet)
{
foreach (Control childCtrl in Ctrl.Controls)
{
ctrlRet = childCtrl.LocateControl(Id);
if (null != ctrlRet)
break;
}
}
return ctrlRet;
}
}
Calling the original method is clunky —
Control ctrl = LocateControl( parentControl, controlId);when compared to the new extension method —
Control ctrl = parentControl.LocateControl( controlId);Very nice.