Home > Development, Tips > Extension Methods

Extension Methods

Have you ever been working with an object in managed code and thought “Boy, it would be nice if this object did this…”. Well, With extension methods, you can sort of append functionality to an existing type without having to use inheritance to create your own object. Now, there are a few caveats to this functionality that you should be aware of.

1. Extension methods must be static.
2. They must be methods. No properties here.


So, let’s take a look at an example. One common feature I get fed up with is that System.Guid does not have a TryParse method. So, let’s add that functionality without creating our own Guid Frankenstein.

public static bool TryParse(this Guid ext, string value, out Guid result)
  bool isValid = false;
            result = Guid.Empty;

                result = new Guid(value);
  catch (OverflowException)
                //eat it
  catch (FormatException)
                //eat it

  return isValid;

It’s not the most beautiful or graceful code ever written, but as long as I reference the namespace of the class where I put this, I can now type System.Guid.TryParse and it is a valid method, which executes my extension.

We use this in our project to do many things, especially with System.DateTime formatting so that we can display “2 days ago” from a System.DateTime rather than showing the date and time.

In MVC, extension methods are useful in creating custom controls by way of extending the HtmlHelper.

public static string Image(this HtmlHelper helper, string id, Uri url, System.Drawing.Size maximumDimensions, object htmlAttributes)
  return BuildImage(id, url, maximumDimensions, htmlAttributes);

private static string BuildImage(string id, Uri url, System.Drawing.Size? maximumDimensions, object htmlAttributes)
  if (url == null)
  throw new ArgumentNullException("url");

            // Create tag builder
  var builder = new TagBuilder("img");

            if (!String.IsNullOrEmpty(id))
                // Create valid id

            // Add attributes
  builder.MergeAttribute("src", url.ToString());
  builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));

            if (maximumDimensions != null)
  System.Drawing.Size imageSize = maximumDimensions.Value;

  //TODO: Modify this code to take in the actual size of the image and compute a scale size
                  builder.MergeAttribute("width", imageSize.Width.ToString());

            // Render tag
            return builder.ToString(TagRenderMode.SelfClosing);

Then, on my view, I can use

<%= Html.Image("MyId", Url.Content("~/Content/Images/MyImage.jpg"), new Size(200,200), new { alt="My Image" }) %>

And the page will render out my image tag with all my attributes set the way I wanted. Pretty handy.

Categories: Development, Tips Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: