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…
3 Responses to C#.NET – How to extend the .NET Framework easily (extension Methods)
ASP.NET MVC C# Linq to Stored procedure with Dynamic Query (a quick phone book, piece of Cake !) | blog.dervalp.com
June 12th, 2009 at 2:53 pm
[...] Back to our Filters, the magic word here is “this”. You create a static class with an Ubiquitous Language (DDD style, traduction explicit name) and you create some static methods. In this example, it is “this IQueryable<UserDB>” and if you play with an object of that type, the intellisense will detect automatically and will show it to you (Like we saw in a previous post, here). [...]
kelvin
June 22nd, 2009 at 5:37 am
Why is your method named “IsNotEmail” – when clearly you are looking for “IsEmail”…
or am i missing something?
kelvin
June 22nd, 2009 at 5:39 am
Ohh and one more thing, I just tried this in my VS2005, and I don’t think VS2005 understands this construct. Does this only work in 2008 or 2010? I will try it later on those versions of VS.
Great find, btw