Blog of a Filipino Developer about C#, VB.NET, ASP.NET, Java, PHP, SQL Server, MySql and Oracle RSS 2.0
 Saturday, January 05, 2008

One of the cool feature (if used correctly) added to .NET 3.x is Extension Methods which enables you to extend an specific type by adding your own methods to it. It's useful in cases where you want to extend a library that you dont have access to the source.

To demonstrate extension methods lets look at a code that i used in a previous blog post.

string gravatarUrl = "http://www.gravatar.com/avatar.php?gravatar_id";
string gravatarID = Utilities.Strings.ToMD5("keith.rull@gmail.com");
Image1.ImageUrl = String.Format("{0}={1}",gravatarUrl,gravatarID);

As you can see, I am using a static class that has a method called ToMD5() that converts my string into MD5. Nothings wrong with the implementation of the code except that it would look cleaner if the string object automatically contains the ToMD5() method instead of calling Utilities.Strings.ToMD5(). This is when extension methods come in handy.

My usual approach when using Extension Methods is creating a seperate class library project that would contain classes for each extension type (e.g StringExtensions, ObjectExtensions, ListExtensions..). This approach makes sure that I don't confuse myself with what extensions I have added to my project and where to find them when I need to modify one of them. I would then reference that library to my project as seen below.

Now lets look at the nuts and bolts on how to create an extension method but first lets look at how I implemented the code sample on our converting a string MD5 article.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace KeithRull.CreatingExtensionMethods
{
   public class Utilities
   {
      public class Strings
      {
         /// <summary>
         /// A method that converts a string to MD5
         /// </summary>
         /// <param name="stringToConvert">the string to convert</param>
         /// <returns>the MD5 hashed string</returns>
         public static string ToMD5(string stringToConvert)
         {
            //create an instance of the MD5CryptoServiceProvider
            MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();

            //convert our string into byte array
            byte[] byteArray = Encoding.UTF8.GetBytes(stringToConvert);

            //get the hashed values created by our MD5CryptoServiceProvider
            byte[] hashedByteArray = md5Provider.ComputeHash(byteArray);

            //create a StringBuilder object
            StringBuilder stringBuilder = new StringBuilder();

            //loop to each each byte
            foreach (byte b in hashedByteArray)
            {
               //append it to our StringBuilder
               stringBuilder.Append(b.ToString("x2").ToLower());
            }

            //return the hashed value
            return stringBuilder.ToString();
         }
      }
   }
}

What we need to do to convert the code to an extension method is modify its parameter to include the this keyword right before the data type declaration. The this keyword when used as part of a parameter tells the compiler that this extension is only applicable to objects of type string. Please also note that the method should be static to be able to use it as an extension method.

The code below is converted version of our ToMD5 extension method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace KeithRull.Extensions
{
   public static class StringExtensions
   {
      /// <summary>
      /// Converts the string to MD5
      /// </summary>
      /// <param name="stringToConvert">referrs to itself</param>
      /// <returns>the md5 hashed string</returns>
      public static string ToMD5(this string stringToConvert)
      {
         //create an instance of the MD5CryptoServiceProvider
         MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();

         //convert our string into byte array
         byte[] byteArray = Encoding.UTF8.GetBytes(stringToConvert);

         //get the hashed values created by our MD5CryptoServiceProvider
         byte[] hashedByteArray = md5Provider.ComputeHash(byteArray);

         //create a StringBuilder object
         StringBuilder stringBuilder = new StringBuilder();

         //loop to each each byte
         foreach (byte b in hashedByteArray)
         {
            //append it to our StringBuilder
            stringBuilder.Append(b.ToString("x2").ToLower());
         }

         //return the hashed value
         return stringBuilder.ToString();
      }
   }
}

As said in the previous paragraph, my usual practice is creating a seperate project for my extensions which in this case is called KeithRull.Extensions. Now if you want to use the extension all you need to do is reference the KeithRull.Extension in your class file and the magic extension methods will do the rest

One thing to note about extension methods is that it can be subject to abuse (specially if placed in the hands of people who are addicted to new features without really understanding the real value of its usefulness) so only use it when necessary because extension methods can lead to code bloat.

Saturday, January 05, 2008 12:42:16 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET
Archive
<January 2008>
SunMonTueWedThuFriSat
303112345
6789101112
13141516171819
20212223242526
272829303112
3456789
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2008
Keith Rull
Sign In
Statistics
Total Posts: 260
This Year: 57
This Month: 0
This Week: 0
Comments: 116
Themes
Pick a theme:
Ads
All Content © 2008, Keith Rull
DasBlog theme 'Business' created by Christoph De Baene (delarou)