Introduction

In this article, we will take a look at what extension methods are and how to use them in .NET. Personally, they are one of the best things that have been introduced into the .NET Framework in terms of readability. I will take you through what extension methods are, how to create them (in C# and VB), then I will show you some of the extension methods that I have created (in C# only, conversion is for you to try).

Contents

Extension methods allow you to easily extend a type, such as an integer or string, without re-compiling or modifying the type. In essence, they are a type of static (shared in VB) method, but they are called as if the method is native to the type. Extension methods are available from the 3.5 version of the .NET Framework and can be implemented on any type in the .NET Framework or any custom type that you define.

One downside to extension methods is if that you create an extension method with the same name as another method in that type, the compiler will bind the method call to the native method, not any extension. An extension method is only called when there is no native method found.

Warning

If you declare an extension method on the type Object, you will effectively create the extension method for every type in the framework including but not limited to String, Integer and Lists.

The basic outline of creating an extension methods goes something like this:

Create a public static class (module in VB)

Define functions that you wish to perform

Make the functions an extension method

Following through a complete example, I will now demonstrate how to create an extension method that returns the first 3 characters of a string. Using the list above, I must first create a static class or module:

// C#
publicstaticclass Extensions
{
}

' VB
Module Extensions
EndModule

The next phase would be to write the function that we are going to need, which in this case is the following:

So far, we have done nothing special. The last phase is to make the functions' extension methods. It is slightly more complicated in VB, but not by much. I will deal with C# first.

To make our C# version of our function, we need an extension method to mark the function as static (so that it can be accessed at any time without the need for declaring anything) and secondly, mark the first parameter with the this keyword. This keyword basically tells the CLR that when this extension method is called, to use "this" parameter as the source. See the following:

Now for the VB version. Instead of using the this keyword, we need to do something slightly different. We need to mark the function with the System.Runtime.CompilerServices.Extension attribute like so:

Here are a few of the extensions that I have found or created over time. These are helpful to me and I hope they are to you as well. If you have a question about any of these, drop me a comment below.

HasElements

Something that I often do is check a collection for a value. This method is designed to prevent me constantly checking for a null value and existence of any item in a given collection. This method will work on any collection that implements the ICollection interface.

Each

Quite often, I have to perform a task on a collection of items. This is just a shortcut way for saying for each element in the collection, perform this action. This will work on any collection that implements the ICollection interface. The action that is parsed in can be a lambda expression or a function/subroutine.

Definition:

///<summary>/// Executes the given action against the given ICollection instance.
///</summary>///<typeparamname="T">The type of the ICollection parameter.</typeparam>///<paramname="items">The collection the action is performed against.</param>///<paramname="action">The action that is performed on each item.</param>publicstaticvoid Each<T>(this ICollection<T> items, Action<T> action)
{
foreach (T item in items)
{
action(item);
}
}

In

Often it is necessary to determine whether a value is in a set collection. For example, I need to check whether a string is in an allowed list. This method will allow us to check any value against an array of values of the same type.

Definition:

///<summary>/// Determines whether a parameter is in a given list of parameters.
/// E.g.. 11.In(1,2,3) will return false.
///</summary>///<typeparamname="T">The type of the source parameter.</typeparam>///<paramname="source">The item that needs to be checked.</param>///<paramname="list">The list that will be checked for the given source.</param>publicstaticbool In<T>(this T source, params T[] list)
{
if (null == source) thrownew ArgumentNullException("source");
return list.Contains(source);
}

Hopefully, you now have an understanding of how to implement extension methods in both C# and VB.NET. If you need any help with your extension methods or if you would like to ask a question, drop me a comment below.

Share

About the Author

I am a self-taught programmer originating from the Isle of Wight. I have approximately 3 years commercial experience in developing LOB applications for a wide range of customers (local companies to FTSE 100). During this time, I have honed my development skills across a wide range of platforms and frameworks including C#, VB.net, T-SQL, Web Services and Android programming.