1. Home
  2. Computing & Technology
  3. Visual Basic
Dan Mabbutt
Dan's Visual Basic Blog

By Dan Mabbutt, About.com Guide to Visual Basic

The Magic Incantation for Extension Methods

Saturday September 19, 2009

You won't find it in Microsoft's documentation!

(Sanity Warning! Extension methods aren't explained in this blog. For that, you have to wait for the main article now in progress.)

 All of Microsoft's documentation ... and the documentation in other sources as well ... are careful to point out that an extension method has to be in a Module, not a Class. And you have to Import the namespace for the method in the consuming project. Those details are important, because they're things you wouldn't know otherwise and you might beat your head against a wall for a long time wondering why your code doesn't work if you didn't know.

But the natural way to use something like extension methods is as part of an object library that somebody else has coded. You add a reference for the namespace to your project and you're good to go.

Or are you?

There is no such thing as a "Module Library" ... .NET only provides "Class Libraries". You can include a Module in a Class Library and build a .DLL (using the examples found in books and on MSDN) and then add a Reference to that .DLL into your project. But it still doesn't work! You get a "not found" error message when you reference the extension method in your code. Arrggghhhh!

To make it work, you have to hold your left ear, sing "Oh Susanna" in the key of G and hop around on one foot while you're typing the code.

Seriously, the Module and the method both have to be declared as Public or it won't work.

Not a big thing, but I faunched around with that for more than a few minutes before I discovered it. After you figure it out, there is a sort of logic. But on the other hand, you don't have to use the "Me" qualifier in the method parameter while C# does require the "this" qualifier (C# syntax for "Me") preceding the method in their syntax. Consistency is such a wonderful thing. Rare, but wonderful nonetheless.

When Microsoft marketing types talk about this sort of thing, they describe it as "a rich, robust development environment". I call it "confusing".

Comments
November 11, 2009 at 5:20 pm
(1) Ryan says:

Thanks for this post! I searched Google for a bit when I came across your post. Good show.

Leave a Comment

Line and paragraph breaks are automatic. Some HTML allowed: <a href="" title="">, <b>, <i>, <strike>

Explore Visual Basic
By Category
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Visual Basic

©2009 About.com, a part of The New York Times Company.

All rights reserved.