Language Feature Highlight: Extension Methods

Welcome to this installment of the .NET Nuts & Bolts column. Learn to highlight the extension methods language feature that has been added to the C# 3.0 and Visual Basic 9.0 languages. You’ll touch on what they are, the syntax behind them, and why they are relevant.

Extension Methods Defined

One of the core tenets of object-oriented programming is inheritance. Inheritance is the ability to derive, also known as extending, a new type from an existing type and override or extend existing behavior from the original type. Microsoft .NET supports this and additionally offers the ability to mark classes as sealed so that they cannot be inherited if you do not wiant them to be. Objects need to be designed for inheritance to ensure derived classes aren’t broken in subsequent versions of a base class.

C# 3.0 and Visual Basic 9.0 introduce a new syntax that allows you to conceptually extend an existing type by adding new methods to the type without deriving a new type. This applies to both value and reference types. The end result is that any existing type can be extended regardless of whether if it is inheritable or not. Extension methods must be both public and static. They must be in a top-level class and cannot be a nested class. They allow you to add behaviors to an existing type as if it is just another member of that type.

Extension methods are one of the language feature components along with type inference, partial methods, anonymous types, lambda expressions, and other features that enable Language Integrated Query (LINQ). The unified data querying capability adds significant features. Future articles are likely to have much more on LINQ as it is a unified mechanism for querying data regardless of whether it is from a database, XML, file system, or other source.

Extension Methods in C#

The syntax for creating an extension method within C# involves putting the this keyword in front of the type for the first parameter. Behind the scenes, the C# compiler is decorating the methods with the Extension attribute. Once defined, the method extension is then used through classic method calls or as if it is defined inside the type. The sample code below will demonstrate the syntax for defining extension methods on the decimal type and demonstrate their use in C#. I created a new Windows console project to hold the code. Visual Studio 2008 Beta 2 was used to create the examples contained within this article.

namespace CodeGuru.ExtensionMethods
{
   class Program
   {
      static void Main(string[] args)
      {
         ExtensionMethodsSample.Demo();
      }
   }

   static class ExtensionMethodsSample
   {
      public static decimal Triple( this decimal d )
      {
         return d * 3;
      }

      public static decimal Half( this decimal d )
      {
         return d / 2;
      }

      public static void Demo()
      {
         decimal x = 14M;
         decimal y = 14M;

         // Classic method call to be read from inside out
         x = Half(Triple(x));

         // Using the extension method as if it is defined
         // on the decimal type
         y = y.Triple().Half();

         Console.WriteLine("x is {0}", x);
         Console.WriteLine("y is {0}", y);
         Console.ReadLine();
      }
   }
}

Extension Methods in Visual Basic

In Visual Basic, extension methods must be defined within a module. The containing module and the method itself must be decorated with the Extension attribute. C# automates the decoration of this attribute; however, in this instance Visual Basic requires the programmer to do the work. The first parameter type to the method is the type that the method extends. The sample code below will demonstrate the syntax for defining extension methods on the Decimal type and demonstrate their use in Visual Basic.

Imports System.Runtime.CompilerServices

Module Module1

   Sub Main()
      ExtensionMethodsSample.Demo()
   End Sub

End Module

<Extension()> _
Public Module ExtensionMethodsSample
   <Extension()> _
   Public Function Triple(ByVal d As Decimal) As Decimal
      Return d * 3
   End Function

   <Extension()> _
   Public Function Half(ByVal d As Decimal) As Decimal
      Return d / 2
   End Function

   Public Sub Demo()
      Dim x As Decimal = 14.0
      Dim y As Decimal = 14.0

      REM Classic method call to be read from inside out
      x = Half(Triple(x))

      REM Using the extension method as if it is defined
      REM on the decimal type
      y = y.Triple().Half()

      Console.WriteLine("x is {0}", x)
      Console.WriteLine("y is {0}", y)
      Console.ReadLine()
   End Sub
End Module

Summary

This article covered the extension methods language feature. You examined what they are along with the syntax for using them using an example extending the decimal type. Extension methods are one of the language features along with type inference, partial methods, and others that enable Language Integrated Query (LINQ) to be possible, so it is important to understand them.

Future Columns

The topic of the next column is yet to be determined. It is likely I will cover another upcoming language feature. If you have something in particular that you would like to see explained here, you could reach me at mstrawmyer@crowechizek.com.

About the Author

Mark Strawmyer, MCSD, MCSE, MCDBA is a Senior Architect of .NET applications for large and mid-size organizations. Mark is a technology leader with Crowe Chizek in Indianapolis, Indiana. He specializes in architecture, design, and development of Microsoft-based solutions. Mark was honored to be named a Microsoft MVP for application development with C# for the fourth year in a row. You can reach Mark at mstrawmyer@crowechizek.com.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read