Programming Basics

Extension Methods

Extension methods in C# are a way to expand the functionality of a class without creating new derived types.

You need to be careful when you use an extension method, once you start it’s very easy to just make everything into an extension.

Try to be controlled, only make an extension method if you really need to. Usually this is to add functionality to classes you do not control the source code to. You also want to only add an extension that makes sense for the whole problem domain. Don’t extend int to give values relating to time, or other such oddness.

The most common modern use is to create new Html Helpers in MVC.

namespace MyProject.Extensions
  public static class HtmlHelperExtensions
    public static string BeHelpful(this HtmlHelper helper)
      return "I'm Helping";

To use this extension in your view, you need to make sure that the namespace it’s in is included in the ~/Views/web.config file. You will also need to reference the namespace with a using directive.

@using MyProject.Extensions

If you want to pass additional data to your helper, then you would include these parameters in the method definition

public static string ShortenString
  (this HtmlHelper helper, string value)
      value.Length() > 10 ? value.Substring(0, 10) : value;

One further thing to consider, when creating extensions you cannot override an existing method, if you attempt to do this it will not work, the original method will always be called.

So, use extension methods carefully, otherwise you will clutter up your code. They are useful, but not a cure to all your problems.

Leave a Reply

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

You are commenting using your 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