Add Methods to Existing Classes (Extension Methods)

You can add custom features to an existing type as if the type always had the custom features. In this way, you do not have to recompile a given class, nor do you have to create a second derived class to add these features. Rather, you can add a method to an existing class by using a compiler feature called extension methods.

Adding methods varies between Visual Basic and C#. In Visual Basic, you first import the System.Runtime.CompilerServices namespace into your code file. Next, you mark a given Sub or Function with the ExtensionAttribute directive. Lastly, you write a new Sub or Function with the first parameter of the new method being the type you want to extend. The following shows an example. In this example, we extend the Integer type with a new method called DoubleInSize. The compiler knows we are extending the Integer class because this method is marked as Extension, and the first parameter in the method takes an Integer value.

VB

Imports System.Runtime.CompilerServices

Public Module IntegerExtensions
  <Extension()>
  Public Function DoubleInSize(ByVal i As Integer) As Integer
    Return i + i
  End Function
End Module

The C# compiler does not require the same import or method attribute. Instead, you first create a static class. Next, you create a static method that you intend to use as your extension. The first parameter of your extension method should be the type you want to extend. In addition, you apply the this modifier to the type. Notice the following example. In it, we extend the int data type with a new method called DoubleInSize:

C#

namespace IntegerExtensions
{
  public static class IntegerExtensions
  {
    public static int DoubleInSize(this int i)
    {
      return i+i;
    }
  }
}

To use an extension method, you must first import (using in C#) the new extension class into a project. You can then call any new method as if it had always existed on the type. The following is an example in both Visual Basic and C#. In this case, a function called DoubleInSize that was defined in the preceding example is being called from the Integer (int) class.

VB

Imports IntegerExtensions

Module Module1
  Sub Main()
    Dim i As Integer = 10
    Console.WriteLine(i.DoubleInSize.ToString())
  End Sub
End Module

C#

using IntegerExtensions;

namespace CsEnhancements
{
  class Program
  {
    static void Main(string[] args)
    {
      int i = 10;
      Console.WriteLine(i.DoubleInSize().ToString());
    }
  }
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset