C#: Extension Methods for Generics


Extension methods is a powerful feature of C#, allowing you to extend the functionality of existing types. The syntax for this is fairly simple for integers, strings and other types, but you can also use extension methods for generics. Before we do that, let’s review how extension methods work with a simple example.

Extension methods should be written in a new static class. The method itself should be static too. The first parameter is preceded by the ‘this’ keyword which specifies the type this extension method should be applied on. The following example writes a simple extension method for the int type.

    public static class Extensions
        public static int Increment(this int originalValue, int increment)
            return originalValue += increment;

Add a “using” statement at the top of the class where you plan on using this extension method. The using statement should reference the namespace where the extension method is declared. After that, you can declare an int variable and use the extension method directly on the variable!

int test = 10;
Console.WriteLine(test.Increment(5).ToString()) ;

Note that you don’t need to specify two parameters. the originalValue argument in the extension method references to the test variable (hence the “this” keyword), the only argument you need to specify is the increment value. When you run the console application, you should see 15 printed out to the console.

You could of course simply write

Console.WriteLine(test += 5);

but this was just a simply (and unpractical) example. Now we’ll write a more usefull extension method which can be used on a generic list.

Generics is a powerful feature of C#, allowing you to write highly reusable code by not having to specify an object type. It’s mostly used with Collections. The generic part of a generic list is are the brackets, where T denotes the object type. The compiler generates code to handle the list, regardless of the object type. For example, if you create a list of of Blog objects, you can easily retrieve a blog object by using an index. If you don’t use a generic list, you would store and retrieve objects (not  Blogs), and you’d need to do additional boxing/unboxing which might consume a lot of memory when doing it frequently. If you’re not so familiar with generics, &&/|| my explanation is confusing, read up on Generics on MSDN

I use Lists quite often, and I’m often annoyed when having to add many items to a List, because the Add method of a list only expects one argument. Time to write an extension method for that. We’ll specify an overload for the Add function, giving us the ability to add multiple items (by using the params[] keyword). This is the code for the extension method, defined in another class.

public static class ListExtensions
        public static void Add(this List list, params T[] item)
            foreach (var listItem in item)

The <T> type of this extension method is the same as the type of the list this method is called on. You can add as many items as arguments to an array of T objects. The above code loops trough this array and adds each item to the list.
You can implement this extension method in two different ways. We’ll look at these, and at how we would do this without an extension method.

List<string> list = new List<string>();

With Extension Method

List<string> list = new List<string>();
list.Add("this","is", "the", "extension", "method");
list.Add<string>("this","is", "the", "extension", "method");

Extension methods combined with the power of generics (and your own types) allow you to create some highly reusable code, which always comes in handy.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s