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:
Function DoubleQuote(Extends s As String) As String Return """" + s + """" End Function
Of course, you can also extend regular classes as well. This example extends ListBox to add a search function that will search and select a row that contains a specific column value:
Sub Find(Extends lb As ListBox, findText As String, column As Integer) For i As Integer = 0 To lb.ListCount-1 If lb.Cell(i, column) = findText Then lb.ListIndex = i Exit For End If Next End Sub
You use it by supplying the text to find and the column to search in:
ListBox1.Find("MyValue", 1)
Extensions are a great way to make your code more readable and to easily add useful “utility” methods. To learn more about extension methods, refer to the User Guide.
There’s an extension method example that is included with Xojo:
Examples/Language Features/ExtensionMethods