Extension Methods!!!

Posted by Ahmed Tarek Hasan on 11/03/2012 05:29:00 AM with No comments
"Extension methods" was first introduced in .NET 3.5 (C#3/VB9). It is a feature which lets you extend existing classes with new methods without the need to inherit from these classes. These classes are probably to be closed ones without access to their source code, otherwise, why extend the class when I can edit its code freely?!!!

Writing an extension method is so similar to writing a static class which wraps or uses the class which I want to extend. Actually there is always a debate on whether to use static classes or use extension methods. Me myself, I prefer to use extension methods because I think it makes the code more readable as you don't need to break the context to make use of a static method.

To get what I am saying here, suppose that we want to write a method which takes an "int", increment it by 3, multiply it by 5 and finally return the value.

To achieve this, we have 3 approaches:
  1. Writing a static class (IntHelper) with a static method inside (DoCalculations) which takes an int as input parameter (inputNum) and returns the resulting int ((inputNum + 3)*5)
  2. Writing an extension method (DoCalculations) which extends int to do the same job as above
  3. Writing a new class which inherits from int and then adds a new method (DoCalculations) which carries out the too complex calculation we are talking about :)

Now, let's check every approach and come out with a decision on which one we prefer to use.


Writing new class inheriting from int:
I think we all agree that this will be too much and inappropriate :)


Writing static class:
The code will be
  1. public static class IntHelper
  2. {
  3.     public static int DoCalculations(int inputNum)
  4.     {
  5.         return (inputNum + 3) * 5;
  6.     }
  7. }

And to use, the code will be
  1. int currentWidth = this.Width;
  2. MessageBox.Show(IntHelper.DoCalculations(currentWidth).ToString());


Writing an extension method:
The code will be
  1. public static int DoCalculations(this int source)
  2. {
  3.     return (source + 3) * 5;
  4. }

And to use, the code will be
  1. int currentWidth = this.Width;
  2. MessageBox.Show(currentWidth.DoCalculations().ToString());


So, now after we have seen all approaches, I still think that the extension method is more appropriate cause when using the call we didn't break the natural flow.

Finally, this was a brief introduction of extension methods and if you wish to know more you can read Scott Hanselman's post of title "How do Extension Methods work and why was a new CLR not required?"


Update:
Some extension methods are added in separate posts where each post includes extension methods for certain class. Please find these posts below.


Posts:
  1. Catalog
  2. System.String
  3. System.Web.UI.WebControls.WebControl
  4. System.DateTime
  5. System.Linq.IOrderedQueryable
  6. System.IConvertible
  7. Generics (T)


Categories: ,