This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 3.5+

C# Extension Methods

Sometimes it is necessary to add functionality to a library for which you do not own the source code and where using inheritance to subclass functionality is not viable. This problem can be overcome with the careful use of C# 3.0 extension methods.

What is an Extension Method?

An extension method is a type of method that was introduced in C# version 3.0. Extension methods allow you to create new functionality for existing data types, including classes, structures or interfaces, without modifying the code of the type itself. This permits new methods to be created for classes for which you have no access to the source code, including the standard types in the .NET framework libraries or those in third-party assemblies.

In previous versions of the C# language, you could modify the functionality of classes only by inheriting from the existing types and adding functionality in a subclass. However, if the existing classes are sealed this is not possible. With extension methods, you can add functionality to sealed types.

You can create extension methods for base classes in inheritance hierarchies. Any method added to a base class is automatically implemented for all subclasses too. Similarly, an extension method for an interface is added to all types that implement the interface.

Microsoft use extension methods extensively for the language-integrated query (LINQ) system. The standard LINQ operators, such as Select, Where and OrderBy, are extension methods that are added to the IEnumerable and generic IEnumerable(T) interfaces.

Extension Method Limitations

Extension methods do not modify the extended class. They are defined externally and these definitions cannot be used to override existing methods of the type. An extension method will never be called if it has the same signature as an existing class member.

It is important that the principle of encapsulation is not violated by extension methods. To prevent this, extension methods do not have access to any private members of the extended class. They may only work with externally visible members.

It is possible to create two or more extension methods with identical signatures. If two extension methods with matching signatures are visible for the same base class, the code will not compile. This problem can be circumvented by defining the extension methods in separate namespaces and ensuring only one of the namespaces is referenced in a using directive in any single code file.

Creating Extension Methods

Although an extension method is accessed as if it where an instance method of the extended type, it must actually be defined as a static member of a static class. To signify that the new member is an extension method, the first argument must be of the type being modified and must be preceded by the "this" keyword. The first parameter is never used in calls to the method as it represents the object itself.

The declaration uses the following syntax:

public static result-type name(this obj-type obj, type1 param1, ..., typeX paramX)

The result-type specifies the type that will be returned by the extension method. This is identical to the return type of any other method declaration. The first parameter includes two elements; obj-type is the name of the type that will be extended by the method and obj will contain the object when a call is made. The remaining parameters are those that will be included in any call to the method. These are optional.

A Simple Extension Method

To demonstrate the use of extension methods, we can add a new method to the string data type. String is sealed and so cannot be subclassed, giving an interesting example. Our simple extension method will output the contents of the string to the console. To begin, create a new console application.

All extension methods must be declared within a static class. Ideally this would also be in a separate namespace. However, for simplicity in this article's sample code, we will simply create a new static class within the namespace provided by the console application. Add the following class:

public static class SampleExtensionMethods

We can now create the new extension method inside the SampleExtensionMethods class. Note the use of the "this" keyword for the first parameter:

public static void OutputToConsole(this string s)

Now that the extension method has been created, it is visible as an instance member for all strings. We can test this by modifying the Main method of the program so that it creates a new string and calls the new method:

string testString = "Hello, world.";
testString.OutputToConsole();           // Outputs "Hello, world."

If you are using Visual Studio, you will see that the new method appears in the list of members that is displayed by the Intellisense feature. Note that the item has a different icon to the real instance methods, indicating its status as an extension method.

29 October 2008