For example, you want a method who validate if a string is an email or not.
You create a static class, StringExtensions for example, you put it public static and you add a method who take a string and verify if it is a mail or not.
Like this :
</pre>
public static class StringExtensions
{
public static bool IsNotEmail (this string email)
{
var reg = new Regex(@"^(([^<>()[\]\\.,;:\s@\""]+"
+ @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
+ @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
+ @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
+ @"[a-zA-Z]{2,}))$");
if(reg.IsMatch(email))
{
return true;
}
return false;
}
}
<pre>
Now back to the class where you want to use this extension.
After a dot on a string variable, you will see it in the intellisense:

string email = "tralala@something.com";
if (email.IsEmail())
{
//do something
}
That’s awesome, is that not ?
Indeed, when you put the magic word “this” in a static method insided a static class, VS will browse all the methods who take a string object in argument and will add it to intellisense.
How do I use it ?
As soon as I see that I will need a simple method for a particular type very often, I extend this type and add it to a homemade library( which contains all the extension methods I create). Of course put in your library only the standard object of the .NET framework otherwise you will get some compilation errors.
You are now able to use all the power provided by the intellisense.
For example, you have a new developer in your team. He does not need to search in the project where the functions are. He simply put a dot after his variable and he will see what is available. Moreover, if he is new with the .NET Framework, he will believe that it is included by default
.
related link : http://msdn.microsoft.com/en-us/library/bb383977.aspx
I expect my introduction to extension methods was clear, if not, do not hesitate to leave a comment…
Filed under: .NET on June 12th, 2009 | 3 Comments »