Extension Methods inside .NET 3.5

I have just come across Extension Methods inside the new .NET framework and I have to say that they are very cool.  They allow you to extend most if not any type with custom functions which you specify.  The rule is that you must make the class which defines these methods as static, and a little new syntax, then away you go.

So for this example what I did was create an interface called IKnownStringValidator, this interface has a property and one method which accepts the target string to be validated.

Hide Code [-]
    public interface IKnownStringValidator
    {
        string Pattern { get; }
        bool Execute(string s);
    }
{..} Click Show Code

 

I then created a class which inherits from this interface.  The class is called UKPostCodeValidator, and is simply so I can check for valid postcodes.  Nothing too special here and certainly nothing new.

Hide Code [-]
public class UKPostCodeValidator : IKnownStringValidator
    {
        const string m_pattern = "[a-zA-Z]{1,2}[0-9]{1,2}[\\s]?[0-9]{1,2}[a-zA-Z]{1,2}";

        #region IKnownStringValidator Members

        public string Pattern
        {
            get
            {
                return m_pattern;
            }
        }

        public bool Execute(string s)
        {
            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(m_pattern);
            return r.Match(s).Success;
        }

        #endregion
    }
{..} Click Show Code

 

OK, so now for the extension method.  I have called the class StringHelpers and of course this is a static class, and also any method which you define also must be static.  Notice the first argument of the class, it is the syntax to reference the calling instance of that specified type.  You can then reference this instance inside the function block by the named parameter.

 

Hide Code [-]
    public static class StringHelpers
    {
        public static bool ValidateString(this string s, IKnownStringValidator validator)
        {
            return validator.Execute(s);
        }
    }
{..} Click Show Code

 

The implementation of this is where more new syntax and newly legalised code comes in.

Hide Code [-]
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            // The below variable b is set to true with the following statement
            bool b = "WN5 8TJ".ValidateString(new UKPostCodeValidator());
        }
{..} Click Show Code

 

I have seen this used largely inside the MVC tutorials and examples where by developers are extending the HtmlHelper class.  One thing I did was make a quick and dirty function which allowed me to add an accesskey to the outputted anchor link.  I have not figured out the lambdas implementation yet so here is all I did.

Hide Code [-]
        public static string ActionLinkWithAccessKey(this System.Web.Mvc.HtmlHelper helper, string text, string action, string controller, string accesskey)
        {
            string format = "<a href=\"{0}\" accesskey=\"{1}\">{2}</a>";
            format = String.Format(format, "/"+controller + "/" + action, accesskey, text);
            return format;
        }
{..} Click Show Code

 

With the implementation of this code being:

Hide Code [-]
 <%= Html.ActionLinkWithAccessKey("Contact Us", "ContactUs", "Home", "5")%>
{..} Click Show Code

 

 

Cheers,

 

Andrew :-)

Published Sunday, May 25, 2008 3:05 PM by REA_ANDREW
Filed under:

Comments

# buy a first home

Sunday, August 24, 2008 1:15 PM by buy a first home

That is to say, with even bigger tax breaks available for landlords— capital gains tax breaks and negative gearing— first home buyers are still playing on an uneven field. As Colebatch says,“ A smarter policy that would do more for first home buyers would

# investor marketing

Tuesday, September 09, 2008 9:44 PM by investor marketing

This is a great site, I’ll give a fave on faves.com…I’ll be checking back later

Leave a Comment

(required) 
(required) 
(optional)
(required)