Extension methods are a feature of C# 3.0 that is just one of those features which can be easily overlooked.
A lot of .NET old-timers, like myself, who are particularly kept busy on a daily basis trying to meet a project deadline or build the next biggest, baddest Line of Business application (wow.. that just sounds soo sexy doesn’t it?) will often fall back on old practices. .NET has trained me to often create a number of helper classes, such as a StringValidationHelper etc., in order to do things like validating user-entered data. So for instance, I could have a class that looks like the following:
And here’s how you use it:
Nothing too exciting here so far…
But watch out! Here come Extension Methods!
With Extension Methods, I can change add a method onto the string class itself. And it doesn’t matter if the class is sealed!
Here’s my adjusted StringHelper class:
Notice that all I had to do was add the keyword this before the string data argument.
Now I can use the IsValidPhoneNumber method directly from my string variable:
Ah.. that’s more like it. This code now looks a lot less cluttered.
Of course this is a contrived example but nevertheless illustrates how easy it is to use this very cool feature of C#.
Some of you who have been using LINQ may not realize that LINQ itself heavily uses Extension Methods, particularly on the IEnumerable interface. This occurs when you import the System.Linq namespace. Try it out – look at the IEnumerable interface intellisense before and after you import the System.Linq namespace.