Spontaneous Publicity
blogs are the new phone book

Some of My Favorite Extension Methods

March 24, 2008 11:24 by Luke

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:

kick it on DotNetKicks.com
Tags:
Categories:
Actions: E-mail | del.icio.us | Permalink | Comments (39) | Comment RSSRSS comment feed

Comments

March 24. 2008 17:30

John S.

while you're at it, you should write string.HasValue() (maybe extension properties will make it in to C# 4.0 so we can ditch the extra parens):

public static bool HasValue(this string s)
{
    return s != null;
}

then your table cell code can look like this:
if (cssClass.HasValue())
        cell.CssClass = cssClass;
if (columnSpan.HasValue)
        cell.ColumnSpan = columnSpan.Value;

John S.

April 2. 2008 21:16

Pepe

Amazing post!!! Thnx for sharing

Pepe

April 4. 2008 00:40

Gary

One of my favorites... so simple:

public static bool IsNullOrEmpty(this string s)
{
  return String.IsNullOrEmpty(s);
}


if (String.IsNullOrEmpty(myString))
  // do something

becomes:

if(myString.IsNullOrEmpty)
  // do something

Gary

July 26. 2010 03:08

breguet marine

I have searched this information for a long time.

breguet marine

July 26. 2010 03:09

huho handbag

So great , I like it

huho handbag

July 28. 2010 21:07

natural cures for bacterial vaginosis

This is actually the second instance I have discovered your blog in the last few weeks.  Seems like I ought to bookmark it.

natural cures for bacterial vaginosis

August 1. 2010 21:10

dg sunglasses

Sounds great! I really want learn it better.

dg sunglasses

August 10. 2010 16:09

Birgit Whiddon

Very interesting article.  Your web-site is speedily growing to be among my favorites.

Birgit Whiddon

August 15. 2010 14:43

Daryl Bunkers

Wow, I just needed you to know I have added your good site to my Google bookmarks because of your extraordinary blog layout. But seriously, I think your site has one of the freshest theme I’ve came across. It really helps make reading your nice blog a lot easier

Daryl Bunkers

August 17. 2010 00:00

usb data transfer cable

This is a really good read for me, Must admit that you are one of the best bloggers I ever saw.Thanks for posting this informative article.

usb data transfer cable

August 17. 2010 02:08

couple necklace

It is very informative. Thanks for sharing.

couple necklace

August 21. 2010 00:23

chanel messenger bag

Sounds great! I really want learn it better.

chanel messenger bag

August 21. 2010 15:23

Weight Loss for Idiots Reviews

mmmm, I think you may be right in what you have said in this blog post. Whoever there will be many people will disagree with you.

Weight Loss for Idiots Reviews

August 22. 2010 17:29

gfx forum

Great post for us internet enthusiasts, thank you for posting it! Cheers!

gfx forum

August 23. 2010 08:18

Home Permanent Hair Removal

This is really helping me progress. I've been taking notes!

Home Permanent Hair Removal

August 23. 2010 08:18

Home Permanent Hair Removal

This is really helping me progress. I've been taking notes!

Home Permanent Hair Removal

August 23. 2010 08:19

Home Permanent Hair Removal

This is really helping me progress. I've been taking notes!

Home Permanent Hair Removal

August 24. 2010 03:31

motorola bluetooth wireless headset

It is very useful to me. thank you!

motorola bluetooth wireless headset

August 24. 2010 14:00

loan origination system

Before when I was here, I was simply scrolling by what you wrote, In addition I even told my buds because these guys always begin conversations and start fighting constantly.  

loan origination system

August 25. 2010 03:56

NFL Football Jerseys

If I speak in the Cheap Authentic NFL Jerseys tongues of men and of angels, but have not love, I am only a resounding gong or a clanging cymbal. If I have the gift of prophecy and can fathom all mysteries and all Official NFL Jerseys knowledge, and if I have a faith that can move mountains, but have not love, I am nothing. If I give all I possess to the poor and surrender my USA Jerseys Shop body to the flames,but have not love, I gain nothing.Love is patient, NFL Jerseys love is kind. It does not envy, it does not boast, it is not proud. It is not rude, it is not self-seeking, it is not easily angered, it NHL Jerseys keeps no record of wrongs. Love does not delight in evil but rejoices with the truth. It always protects, always trusts, always MLB Jerseys hopes, always perseveres.Love never NHL Hockey Jerseys fails. But where there are prophecies, they will cease; where there are tongues, they will be stilled; where there is knowledge, it will pass away. For we know in part and we prophesy in MLB Baseball Jerseys part, but when perfection comes, the imperfect disappea. When I was a child, I talked like a child, I thought like a child, I reasoned like a child. When I became NBA Basketball Jerseys man, I put childish ways behind me. Now we see but a poor reflection as in a mirror; then we shall see face to face. Now I know in part; then I shall know fully, even as I am fully known.And now these three remain: faith, hope and NFL Football Jerseys love. But the greatest of these is love. http://www.jersey-usa.com/sitemap.html LIJ

NFL Football Jerseys

August 26. 2010 05:55

coral earrings

I really want learn it better.

coral earrings

August 28. 2010 18:42

Brice Bouquin

why not posting more?

Brice Bouquin

August 29. 2010 06:24

Denver Mines

are you using wp for this blog?

Denver Mines

August 30. 2010 02:01

 Towing Sunnyvale

This is something unusual to find on net. I was looking for a reference so that i can do my project work dexterously.. Thanks for the suggestive post.. !!

Towing Sunnyvale

August 30. 2010 03:36

blonde joke

how can I advertise on your blog?

blonde joke

August 30. 2010 04:07

cheap gazebos

So great , I like it

cheap gazebos

August 30. 2010 07:24

seduction affiliates

you may make some money if you add an affiliate program to your blog...

seduction affiliates

August 31. 2010 00:07

jokes

nice blog! keep the good work!

jokes

August 31. 2010 02:43

Miesha Cork

Substantially, the article is actually the freshest on this deserving topic. I harmonise with your conclusions and also can eagerly look forward to your future updates. Saying thanks will certainly not simply just be sufficient, for the exceptional lucidity in your writing. I definitely will directly grab your rss feed to stay privy of any updates. Gratifying work and much success in your business enterprize!

Miesha Cork

August 31. 2010 22:30

gold overmantle mirror

Aw, that was a really top quality post. In theory I'd just like to write just like this too - taking time and real effort to make a nice article... but what can I say... I procrastinate alot and under no circumstances seem to get something done.

gold overmantle mirror

September 1. 2010 19:18

ETF newsletters

it will be great if you post more...

ETF newsletters

September 2. 2010 21:42

nfl jerseys

Perhaps this is one of the most interesting blogs that I have ever seen. Interesting article, Funny comment. Keep it up!  

nfl jerseys

September 2. 2010 22:57

Murray Hassard

That is lots of inspirational stuff. For no reason knew that opinions could be this varied. Thanks for all the enthusiasm to offer you such helpful information here.

Murray Hassard

September 3. 2010 01:32

ETFs

any plan to update this blog?

ETFs

September 3. 2010 08:44

gifts

try to change your template, there are some great ones...

gifts

September 4. 2010 05:12

ETF

nice blog, try posting more!

ETF

September 5. 2010 06:48

ETF newsletters

do you have a different blog where you post more often?

ETF newsletters

September 7. 2010 04:27

Carpet Cleaning Philadelphia

I really like and appreciate your article.Really thank you! Great.

Carpet Cleaning Philadelphia

September 7. 2010 04:29

Carpet Cleaning Philadelphia

Thanks for sharing, this is a fantastic blog post.Thanks Again. Fantastic.

Carpet Cleaning Philadelphia

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading