LP on .NET

June 21, 2009

Extension Methods

Filed under: .NET,C#,Microsoft,Software Development — Larry Parker @ 9:30 pm

One really nice feature introduced in C# 3.0 (.NET 3.5 / Visual Studio 2008) is something called extension methods.  This was a language feature made to support LINQ, but you can also use it to write your own custom extension methods.

For example, with extension methods you can do something like this:

if (!"joe@smith.com".IsValidEmail())
    return false;

Without extension methods, this would not be possible because even if you could subclass from the String type (which you can’t because it’s sealed) and added the IsValidEmail method, the “joe@smith.com” literal would still be a string.

So extension methods can be very helpful in adding new functionality to existing types, but I also find them useful for changing the syntax of existing methods that just don’t seem to “make sense”.   One such method is the String.IsNullOrEmpty static method.

To use this, you need to do something like this:

if (String.IsNullOrEmpty(firstName))

That’s not very “programmer friendly” because you have to indicate the String class, call a method, and then finally pass in the string as the parameter.

Wouldn’t it make more sense to be able to do something like this?

if (firstName.IsNullOrEmpty())

Not only is it less to type, but it’s more intuitive because you’re calling a method on an instance variable, instead of passing the instance variable into a static method.

The good news is that with extension methods, this is very easy to do:

public static Boolean IsNullOrEmpty(this String value)
{
    return String.IsNullOrEmpty(value);
}

This is as simple as it gets because the implementation of this just calls the original static method.  But you can put anything you wish in your own extension methods – it’s your code.

Hope this helps.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: