Useful Extension Methods
page 2 of 4
by Brian Mains
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 22927/ 40

The Anatomy of an Extension Method

The following is an extension method

Listing 1

namespace Nucleo.Primitives
{
  public static class StringExtensions
  {
    public static bool IsMatch(this string value, string regularExpression)
    {
      return Regex.IsMatch(value, regularExpression);
    }
  }
}

Let's look at it in detail.  First, note the usage of the "this" keyword; whatever type that is designated for the property with the "this" keyword is the type that will be extended.  So, in this example, this method is added to the string class.  This means that you could do:

Listing 2

string value = "4545";
Assert.IsTrue(value.IsMatch(@"\d+"));

And this will work.  When you call IsMatch, it invokes our static StringExtensions IsMatch method.  This is a requirement; both the class and method have to be defined as static.  Secondly, the first parameter must be defined with the "this" keyword.  Note one thing; the first parameter defines the type to extend, but the rest of the parameters are the parameters of the instance method on the class.

What I mean by that is IsMatch has one string parameter: regularExpression.  If the method were defined as

Listing 3

public static bool IsMatch(this string value, string regularExpression, 
RegexOptions options) 
{ 
}

You would invoke it as

Listing 4

Assert.IsTrue(value.IsMatch(@"\d+", RegexOptions.None));

So, for every parameter after the "this" parameter, these are the parameters of the method.  Also note that you can use whatever return type you want (void, bool, string) as it's the return type of the method, and you can also define whatever scope you want, though the most beneficial is public scope.

One thing to note: our static extension is defined in the Nucleo.Primitives namespace; this means that you have to define the following using statement for the extension method to even appear

Listing 5

Using Nucleo.Primitives;

Otherwise, the extension method will not appear for any string instances.


View Entire Article

User Comments

Title: RE: Please specify the framework version   
Name: Brendan Enrick
Date: 2008-05-13 9:13:21 AM
Comment:
Yes, extension methods were added in C# 3.0, so this is a new feature.
Title: Please specify the framework version   
Name: Vijil Jones
Date: 2008-05-13 7:38:16 AM
Comment:
Is this new feature in .net 3 ?






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-26 12:26:29 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search