How to work with extension methods in C#

Extension methods enable you to extend the functionality of existing types sans the need of modifying the existing types or creating sub types from them

The C# programming language provides support for extension methods from C# 3.0. An extension method is one that is used to extend the functionality of existing types by adding methods sans the need of creating new derived types. You don’t need to create subclasses of existing classes or recompile or modify your existing classes to work with extension methods. Extension methods improve the readability of your code while at the same time allowing you to extend functionality of existing types.

The common extension methods in .Net include the LINQ standard query operators that adds additional query capabilities to the System.Collections.IEnumerable and System.Collections.Generic.IEnumerable types. Note that you can take advantage of extension methods to extend a class or an interface but you cannot override their methods. The MSDN states: “Extension methods 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.”

Essentially, an extension method is a special type of a static method and enable you to add functionality to an existing type even if you don’t have access to the source code of the type. An extension method is just like another static method but has the “this” reference as its first parameter. You can add as many extension methods as you want to any type. Most importantly, you can also add extension methods to even a value type.

When working with extension methods, keep these points in mind:

Note that it you define an extension method on a type that has the same signature as any other method of the type that you are extending, the extension method will never be called.

Programming extension methods in C#

In this section we will explore how to program extension methods using C#. The following code listing illustrates how an extension method looks like.