1.22. Create and Use Extension Methods

Problem

You need to extend the functionality of a class without relying on inheritance or access to the actual class.

Solution

Create the method (a Sub or Function) you want to add, and then apply the ExtensionAttribute attribute to it.

How It Works

The key to using extension methods is the attribute ExtensionAttribute, which is new to VB 9.0 and located in the System.Runtime.CompilerServices namespace. You must apply this attribute to any method that you want to use as an extension method. Furthermore, you can apply the attribute only to methods defined within a Module.

An extension method extends the functionality of a specific class without actually modifying it. The class being extended is referenced ...

Get Visual Basic 2008 Recipes: A Problem-Solution Approach now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.