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 :-)