Extension Methods were introduced in C# version 3.0 (C# Version 3.0 Specification). Extension methods allow you to add or “extend-to” a pre-existing class a method of some sort. This is particularly useful when you wish extend a method to a type that is defined in C# (or something closed source) without having to create another class and derive another type.

Furthermore, you could encapsulate the multitude of extension classes you create into their own namespace and optionally include the use of the extensions on a class to class and/or file to file basis in the using statements. I’ll let you decide on that at your own discretion. I like to follow this convention in my projects where I need to use extensions:

It’s important to note that the class containing your extension method must be static and the method you are extending must also be static. This is a requirement for extensions methods.

OK. Now that we have the appropriate syntax in our heads for defining an extension method, let’s put what we’ve learned to use. Let’s define a simple extension to the int type that allows us to print the value of the int to stdout:

You can choose optionally which classes you wish to implement this extension based on the namespace where it lives. If you have encapsulated the class in an ‘Extensions‘ namespace like I suggested earlier, then you can simply add it among the using statements of the classes you wish to have access to your extensions:

using Extensions;

Once a class has access to your extension you may call the extension method on any variable of the type you provided an extension for:

int number = 5;
number.PrintInt();

The output to the console will look like this:

It doesn’t get much straightforward than that. If you wish to try out the code explained above here is a link to download the Visual Studio Project (requires Visual Studio 2008. Though, it may work with Visual C# 2008 Express or 2010 Express which are free. I haven’t tested it. You’re welcome to.):

I have taken the time to create another, more advanced, example using the Microsoft.Xna.Framework (this requires XNA 3.1). In the second example we are modifying a Texture2D object to extend a draw method to it. The end result is a sand texture stretched across the game window. Here’s a link to the second example project:

For more guidance and examples you can consult the C# Programming Guide for Extension Methods at MSDN where they provide the general syntax and usage as well as recommendations for when extensions should and should not be implemented.