Visual Basic 9.0 is full of new features. One of them is Extension Methods, which, in the words of Scott Wisniewski
of the VB compiler group, "provide a very powerful and elegant way to inject your own custom functionality into other people's types….Extension Methods enable you to create a method in a module decorated with an attribute and have that method appear as if it was an instance method defined on another type."
Wisniewski recently posted a six-part Extension Methods tutorial on Microsoft's Visual Basic Team blog. He focused on this feature of Visual Basic 9.0 because, well, it is his favorite. Below we link to each part and offer a bit of insight into what is covered.
Part 1: An introduction to Extension Methods describes how they provide "discoverability." In Visual Studio 2005, calling a utility method uses a different syntax than calling an instance method, so programmers must know, ahead of time, whether they are calling a shared utility method written by a third party or an instance method provided directly by a class author, Wisniewski notes. Visual Studio Orcas' Extension Methods merge these types of methods.
Part 2: Rules for consuming Extension Methods provides tips for defining and consuming these methods. Wisniewski points out the differences between Extension Methods in C# and in VB. He also outlines the "precedence levels" that determine which Extension Method takes precedence in the event that two methods conflict.
Part 3: Extension Methods and byval / byref parameters offers a quick look at how the compiler evaluates Extension Methods calls and a hint or two for working with value-type extensions.
Part 4: Extension Methods and late binding explains why Extension Methods do not support late binding -- it is because the methods are closely tied to IntelliSense, which does not work in late-bound scenarios. Wisniewski then points out that, as a result, Extension Methods cannot be called off any expression statically typed as Object.
Part 5: Generics and Extension Methods discusses why Visual Studio Orcas deals with generic Extension methods differently than regular generic methods. "When binding against extension methods we now perform generic type parameter inference in two passes instead of one," Wisniewski writes. "During the first pass we infer types for type parameters referenced by the first argument and during the second pass we infer types for any type parameters referenced by subsequent arguments." There are three reasons for this -- transparency, better use of IntelliSense and improved query support.
Part 6: Extension Methods Best Practices gives seven tidbits of advice, such as putting Extension Methods into their own namespaces and being as specific as possible when extending a type.