Extension Methods - Part 1 - The basics

Extension methods are a powerful way of gluing your own custom functionality onto types you don't own, and make them accessible like static instance methods to the type, instead of creating a wrapper around the type.

The basics

As a very simple example, we might want to have a method on the the simple int type, that evaluates whether the value is an even number.

So we simply create a static method in a static class, and use the C# extension method shortcut this in the method signature, indicating that the compiler needs to perform a little magic for us with the int type, and implement the IsEven check.

namespace Extensions
{
    public static class Extensions
    {
        public static bool IsEven(this int number)
        {
            return number % 2 == 0;
        }
    }
}

Now we can check whether the int is even or uneven with our extension method, here in a test method:

[TestMethod]
public void IsEvenTest()
{
    int even = 2;
    int uneven = 3;

    Assert.IsTrue(even.IsEven());
    Assert.IsFalse(uneven.IsEven());
}

WindowClipping

Notice that the method is marked as an extension method in our intellisense with both an icon with an arrow down and with the (extension) tag, to avoid confusion:

extensionmethods

So what you need to create an extension method is:

  • A static class
  • A static method
  • "this" in the method signature
  • Add the namespace of the extension method to your class

Pretty simple and powerful. In my next post I will look at how this actually works.

Posted April 25, 2008 by Joachim Lykke Andersen
In

Comments [0]   
All comments require the approval of the site owner before being displayed.
OpenID
Please login with either your OpenID above, or your details below.
Name
E-mail
(will show your gravatar icon)
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

Live Comment Preview