Some of My Favorite Extension Methods
There has been some discussion about extension methods and how they should be used and when. Personally, I try to use them when it will increase the readability of my code. A common candidate for extension methods is the static helper method. These mostly take the form of something like:
public static class StringHelper
{
public static string Truncate(string s, int maxLength);
}
And is usually consumed with something like:
string newString = StringHelper.Truncate(myString, 10);
Now, this isn't too bad, but with extension methods, the signature for this method now looks like:
public static string Truncate(this string s, int maxLength)
and is used with syntax like the following:
string newString = myString.Truncate(10);
So I hope you agree that this improves readability and understanding. And it also prevents you from sprinkling "MyHelperClass.MyMethod" calls everywhere.
I thought I would share some of the extension methods that I am finding invaluable.
RenderControl
This method allows you to take and WebControl and render it as a string. This is very useful for html code generation. The method signature for the helper method is:
public static string RenderControl(WebControl control);
Since the syntax to use extension methods is slightly different than static methods, I decided to rename this method to RenderAsString:
publicstatic string RenderAsString(this WebControl control)
{
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
using (HtmlTextWriter tw = new HtmlTextWriter(sw))
{
control.RenderControl(tw);
return sb.ToString();
}
}
}
GetTableCell
This method has many overloads so you can get all of them in the attached download. I will just show one here:
public static void Add(this TableCellCollection cells,
string text, string cssClass, int? columnSpan)
{
TableCell cell = new TableCell();
cell.Text = text;
if (!String.IsNullOrEmpty(cssClass))
cell.CssClass = cssClass;
if (columnSpan.HasValue)
cell.ColumnSpan = columnSpan.Value;
cells.Add(cell);
}
The Syntax for using this is something like:
Table table = new Table();
TableRow tr = new TableRow();
tr.Cells.Add("My Cell", "MyCssClass", 2);
Which is much better than:
tr.Cells.Add(HtmlHelper.GetTableCell("My Cell", "MyCssClass", 2));
These are just a couple of small examples of how I am finding Extension methods a great tool for making code more readable and concise. You can download the source code for both of these methods here: