Using extension methods in C#

One of the most exciting features of the .NET Framework is Extension Methods. Extension methods allow you to extend the functionality of a class without modifying the code of the class itself. This allows you to write methods for a class anywhere outside the class. This is especially useful when there is no access to the code of the original class. For example, you can write a method to extend the System.String class without actually changing the code of the System.String class. (You can't actually change the code of the System.String class) This method will be a static method residing in a static class anywhere in your application.

Extension methods are defined as static methods, but are invoked as instance methods. This is achieved by prefixing the this keyword to the argument passed in the static method. For example, an extension method meant to remove vowels in a string would have a definition like:
public static string RemoveVowels(this string str)
and it would be invoked as:

  1. string str = "Hello";
  2. string newstr = str.RemoveVowels();

A better, more complete example should make matters clearer. In an earlier post, the DirectoryInfo class has been explained, and as has been pointed out, it does not have a method or property which returns its byte size unlike the FileInfo class. So, one can write a method to extend the DirectoryInfo class as under:

  1. public static class ExtensionMethods
  2. {
  3. public static long GetSize(this DirectoryInfo dir)
  4. {
  5. // Initialize to zero
  6. long size = 0;

  7. // Loop through all the subdirectories and files
  8. foreach(DirectoryInfo folder in dir.GetDirectories())
  9. size += folder.GetSize(); // Recursive call
  10. foreach(FileInfo file in dir.GetFiles())
  11. size += file.Length;

  12. return size;
  13. }
  14. }

So one can use this method as an instance method of any DirectoryInfo instance.

  1. DirectoryInfo dir = new DirectoryInfo(@"C:\WINDOWS");
  2. long sizeOfWindowsFolder = dir.GetSize();

Visual Studio 2008 provides IntelliSense support for extension methods, which makes the job of using extension methods very easy. Programmers vary in opinion about the concept of extension methods with most programmers terming it as "advantageous" while some programmers terming it as "a slap in the face of all serious software programmers". I say, as is with everything in technology, it's all up to you, sir!


  1. Ya I totally agree with this fact that there has been a lot of criticism regarding Extension Methods but it's totally unfair to other developers who believe in achieving their intent using the best possible solution rather than sticking to the conventional OOP paradigm.

    Extension methods is surely going to find its way in my blog as well so watch out ..

    Long live Extrension methods !!!

  2. hello... hapi blogging... have a nice day! just visiting here....