Extension: ‘In’ Details

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.

Let’s consider the following piece of code:



Here is the extension method that determines whether a variable of type T is contained in the supplied list of arguments of type T, allowing for more concise code.

Refactored code:

There are some constraints in declaring extension methods. They can be declared by specifying the keyword this as a modifier on the first parameter of the methods. Extension methods can only be declared in non-generic, non-nested static classes.

Extension methods can be accessed in the namespace in which they are declared or if they are imported with the using directive. If there is any collision between an extension method with an existing non extension method at any given time (collisions occur if the signatures of the methods is identical, excluding the first parameter in the extension methods), the non extension method is invoked. Bellow is a simple example to make things clear:

Extension methods should be used only when the traditional techniques are not feasible. I would recommend the use of the inheritance technique where applicable due to a few reasons. One of them is the fact that extension methods are a bit less intuitive since the code is in a separate static class and not grouped with all the members of a given subclass. Still, they provide an excellent way to extend existing libraries and create Frameworks.

More information on extension methods and other new features in C# 3.0 can be found on MSDN and on ScottGu’s blog.