Using Extension Methods

Want a quick and easy way to add capabilities to bulit-in classes and types without subclassing? Try extension methods.

An extension method is a method that is called using syntax that indicates it belongs to another object. For example, say you really don’t like writing code like this that increments an integer value:

downloadCounter = downloadCounter + 1

With an extension method for Integer, you could instead write something like this:

downloadCounter.Add

Essentially, extension methods are global methods that use the Extends keyword to allow you to write the method using dot notation. This describes the first rule, which is that extension methods must be global methods on modules. The extension method for this Add method looks like this:

Sub Add(ByRef Extends i As Integer, amount As Integer = 1)
i = i + amount
End Sub

Since this takes an optional parameter, you could also write:

downloadCounter.Add(5)

to mean

downloadCounter = downloadCounter + 5

There is a lot more you can do with extension methods, but they are particularly useful for adding methods like this to the built-in data types (such as Integer) that are not available for subclassing.

Another good example is adding a DoubleQuote method that can be used to quote strings: