torsdag 27 mars 2008

Use Extensions Methods to create those methods you always wanted...

With C# 3.0 and Visual Studio 2008 Microsoft gave us the power to extend existing classes with our own methods without doing any inheritance, partial classes etc.

This is done using virtual classes and virtual methods together with the new "this" keyword. Example:
namespace myExtensions
{
public static class Extensions
{
   public static int ParseToInt(this string s)
   {
      return int.Parse(s);
   }
}
}


We can now use this method:
string s = "123";
int i = s.ParseToInt();


As you can imagine this is a fantastic feature as we can create our own library of useful methods. One specific method that I've been missing is a generic way to obtain a control in the Repeater ItemDataBound event:
protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
   if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
   {
      ((Literal)e.Item.FindControl("myLiteral")).Text = "Something...";
   }
}


We can now create two useful extensions:
//Method to check whether the current RepeaterItem is of itemType "Item" or "AlternatingItem"
public static bool IsContentItem(this RepeaterItem item)
{
   return (item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.Item);
}

//Method to retrieve a control from the RepeaterItem
public static T FindControl<T>(this RepeaterItem item, string id) where T : Control
{
   return item.FindControl(id) as T;
}


Usage:
protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.IsContentItem())
{
   e.Item.FindControl<Literal>("myLiteral").Text = "Something...";
}
}


Pretty nice huh? :)

Inga kommentarer: