What is Extension Methods

Extension methods is new in .NET 3.5(Visual Studio 2008), and enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

A demo of extension method

When you are using the StringBuilder, it has methods of AppendLine or AppendFormat, but it is a pit that when you are using AppendLine, you cannot use the format. Here is a demo, that we use the extension method to add our ‘AppendFormatWithLine’ method, and use it as methods given by .Net framework.

   1:  namespace ConsoleApplication2
   2:  {
   3:      class Program
   4:      {
   5:          static void Main(string[] args)
   6:          {
   7:              StringBuilder sbValue = new StringBuilder();
   8:              sbValue.AppendFormatWithLine("Welcome to {0}", "http://jack-fx.com");
   9:   
  10:              Console.WriteLine(sbValue);
  11:          }
  12:      }
  13:   
  14:      public static class StringBuilderExtension
  15:      {
  16:          public static void AppendFormatWithLine(this StringBuilder sb, string format, params object[] args)
  17:          {
  18:              sb.AppendFormat(format, args);
  19:              sb.AppendLine();
  20:          }
  21:      }
  22:  }

You will see, call the extension method ‘AppendFormatWithLine’ is as easy as you can imagine.

Rules and Guidelines to use Extension Methods

  • C# supports extension methods only, and does not offer extension extension operators, properties, extension
    events, and so on.
  • Extension methods must be declared in non-generic, static classes. However, there is no restriction on the name of the class; you can call it whatever you want. Of course, an extension method must have at least one parameter, and only the first parameter can be marked with the this keyword.
  • C# compiler looks only for extension methods defined in static classes that are themselves defined at the file scope. In other words, if you define the static class nested within another class, the C# compiler will emit an error message.
  • Since the static classes can have any name you want, it takes the C# compiler time to find extension methods as it must look at all the file-scope static classes and scan their static methods for a match. To improve performance and also to avoid considering an extension method that you may not want, the C# compiler requires that you “import”extension methods. For example, if someone has defined a StringBuilderExtension
    class in one namespace, then a programmer who wants to have access to this class’s extension methods must put a using namespace; directive at the top of the source code file.
  • It is possible that multiple static classes could define the same extension method. If the compiler detects that two or more extension methods exist, then the compiler issues an error message(error CS0121). To fix this error, you must modify your source code. Specifically, you cannot use the instance method syntax to call this static method anymore; instead you must now use the static method syntax where you explicitly indicate
    the name of the static class to explicitly tell the compiler which method you want to invoke.
  • You should use this feature sparingly, as not all programmers are familiar with it. For example, when you extend a type with an extension method, you are actually extending derived types with this method as well. Therefore, you should not define an extension method whose first parameter is System.Object, as this method will be callable for all expression types and this will really pollute Visual Studio’s IntelliSense window.