"As the name implies, extension methods extend existing .NET types
with new methods."
Extension methods sound like a last resort form of extensibility since
they are apparently hard to discover in the code, but nonetheless the
idea is cool and could come in handy in the future. Obviously LINQ is
handy :)
Most of the examples that you must've seen pick on the string class.
Here is an example of adding an IsValidEmailAddress method onto an
instance of a string class:
class Program
{
static void Main(string[] args)
{
string customerEmailAddress = "te...@test.com";
if (customerEmailAddress.IsValidEmailAddress())
{
// Do Something...
}
}
}
public static class Extensions
{
public static bool IsValidEmailAddress(this string s)
{
Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]
{2,4}$");
return regex.IsMatch(s);
}
}
The extension methods need to be static methods in a static class
within a namespace that is in scope as shown above. The this keyword
in front of the parameter string s makes this an extension method.
String.IsNullOrEmpty
One of the coolest things about the new string class in .NET 2.0 is
the addition of the IsNullOrEmpty method. Now if that wasn't in there,
we could do it with Extension Methods. In fact, since IsNullOrEmpty is
currently a static method, we can go ahead and add the extension
method anyway since it works on class instances. Let's go crazy and
have it call Trim(), too :)
class Program
{
static void Main(string[] args)
{
string newString = null;
if (newString.IsNullOrEmpty())
{
// Do Something
}
}
}
public static class Extensions
{
public static bool IsNullOrEmpty(this string s)
{
return (s == null || s.Trim().Length == 0);
}
}